标签:字符 pre 接下来 ams 实现 思路 images bfs int
8 8 .@##...# #....#.# #.#.##.. ..#.###. #.#...#. ..###.#. ...#.*.. .#...### 6 5 .*.#. .#... ..##. ..... .#... ....@ 9 6 .#..#. .#.*.# .####. ..#... ..#... ..#... ..#... #.@.## .#..#. 0 0
10 8 -1
思路:广搜。
1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 #include<queue> 5 using namespace std; 6 struct node{ 7 int h,z,step; 8 }cur,net; 9 queue<node>s; 10 char a; 11 int map[30][30]; 12 bool vis[30][30]; 13 int d[5]={1,0,-1,0,1}; 14 int n,m; 15 int sx,sy,ex,ey; 16 void bfs() 17 { 18 if(sx==ex&&sy==ey) 19 { 20 printf("0\n");return ; 21 } 22 while(!s.empty())s.pop(); 23 cur.h=sx; 24 cur.z=sy; 25 cur.step=0; 26 s.push(cur); 27 vis[cur.h][cur.z]=1; 28 while(!s.empty() ) 29 { 30 cur=s.front() ; 31 s.pop() ; 32 for(int i=0;i<4;++i) 33 { 34 int xx=cur.h +d[i]; 35 int yy=cur.z +d[i+1]; 36 if(xx>0&&yy>0&&xx<=n&&yy<=m&&map[xx][yy]!=1&&!vis[xx][yy]) 37 { 38 if(xx==ex&&yy==ey) 39 { 40 printf("%d\n",cur.step+1); 41 return ; 42 } 43 net.h=xx; 44 net.z=yy; 45 net.step=cur.step+1; 46 vis[xx][yy]=1; 47 s.push(net); 48 } 49 } 50 } 51 printf("-1\n"); 52 } 53 int main() 54 { 55 scanf("%d%d",&n,&m); 56 while(n!=0&&m!=0) 57 { 58 memset(vis,0,sizeof(vis)); 59 memset(map,0,sizeof(map)); 60 for(int i=1;i<=n;++i) 61 for(int j=1;j<=m;++j) 62 { 63 cin>>a; 64 if(a==‘@‘){sx=i;sy=j;} 65 else if(a==‘*‘){ex=i;ey=j;} 66 else if(a==‘#‘){map[i][j]=1;} 67 } 68 bfs(); 69 scanf("%d%d",&n,&m); 70 } 71 return 0; 72 }
标签:字符 pre 接下来 ams 实现 思路 images bfs int
原文地址:http://www.cnblogs.com/mjtcn/p/6758401.html