TOJ---3128---bfs(打印路径)

lol 又一次到l 白银I 累死了 打了好多盘......

刚刚看完 比利时 俄罗斯 又是0:0

破产的节奏 这样下去

贪吃蛇啊贪吃蛇

想起 sex god发的贪吃蛇图片 好 流弊的  姑娘 看了会心动 =-=

这题嘛 首先

  touch me

先讲个和这题很重要的东西 坐标  我一开始 全部敲完之后 发现 输出一行空的 。。。

找了好久 才发现 w e s n这4个方向 所对应的坐标搞错了 好伤的。。。

关于 bfs 有人喜欢用数组模拟队列 queue[size]然后通过head tail进行操作 优点很明显 节省时间

但我个人还是 喜欢用 stl中的queue

还有 有人会用 结构体存储信息 有人是用分开的数组存储  个人更加 推荐 结构体

嗯 还有一点就是  有时候 对于vis数组的使用 它的标志 只是为了帮助我们进行理解 因为你同样可以将该点设置为 墙 (即不可通过)就可以了

但因为可以设置为bool 所以也不在乎那么点内存了

然后 打印路径的时候 更推荐使用 string 比char数组 感觉 更加方便 string的初始通过 “”来实现 记得有篇map题目那边也用到了

然后 因为c++为我们重置了运算符 所以可以简单地 通过'+' .'='这些符号操作

最后 贴代码--------今晚  又不能睡了 C罗比赛6点 要是3点就好了 ------明天 还开 班会 =-=

 1 // bfs
 2 #include <iostream>
 3 #include <cstring>
 4 #include <queue>
 5 #include <string>
 6 using namespace std;
 7 
 8 int n , m;
 9 const int size = 110;
10 int dir[4][2] = {1,0,-1,0,0,-1,0,1};
11 char pos[4] = {'S','N','W','E'};
12 char maze[size][size];
13 bool vis[size][size];
14 struct mp
15 {
16     int x;
17     int y;
18     string step;
19 }st,end;
20 bool flag;
21 
22 void bfs()
23 {
24     memset( vis , false , sizeof(vis) );
25     queue<mp>qe;
26     while( !qe.empty() )
27         qe.pop();
28     qe.push(st);
29     vis[st.x][st.y] = true;
30     while( !qe.empty() )
31     {
32         mp now = qe.front();
33         qe.pop();
34         if( maze[ now.x ][ now.y ] == 'E' )
35         {
36             flag = true;
37             end.step = now.step;
38             break;
39         }
40         for( int i = 0 ; i<4 ; i++ )
41         {
42             int xx = now.x + dir[i][0];
43             int yy = now.y + dir[i][1];
44             if( xx<n && xx>=0 && yy<m && yy>=0 && maze[xx][yy]!='#' && !vis[xx][yy] )
45             {
46                 mp next;
47                 next.x = xx;
48                 next.y = yy;
49                 next.step = now.step + pos[i];
50                 qe.push(next);
51                 vis[next.x][next.y] = true;
52             }
53         }
54     }
55 }
56 
57 int main()
58 {
59     while( cin>>n>>m )
60     {
61         flag = false;
62         memset( maze , '#' , sizeof(maze) );
63         for( int i = 0 ; i<n ; i++ )
64         {
65             for( int j = 0 ; j<m ; j++ )
66             {    
67                 cin>>maze[i][j];
68                 if( maze[i][j]=='S' )
69                 {
70                     st.x = i;
71                     st.y = j;
72                     st.step = "";
73                 }
74             }    
75         }
76         bfs();
77         if( !flag )
78             cout<<"Can't eat it!"<<endl;
79         else
80             cout<<end.step<<endl;
81     }
82     return 0;
83 }
View Code

today:

  我们每个人来到世界上 都是独自旅行 即使有人相伴 终究各奔东西  

just follow your heart
原文地址:https://www.cnblogs.com/radical/p/3803334.html