BFS
2016-02-04 22:03
246 查看
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <queue> using namespace std; struct node { int x,y,step; }; char map[105][105]; bool vis[105][105]; int dir[4][2]= {{1,0},{-1,0},{0,1},{0,-1}}; int n,m,sx,sy,ex,ey,ans; int check(int x,int y) { if(x<0 || x>=n || y<0 || y>=m) return 1; if(vis[x][y] || map[x][y]=='#') return 1; return 0; } void bfs() { int i; queue<node> q; node a,next; a.x = sx; a.y = sy; a.step = 0; vis[a.x][a.y]=true; q.push(a); while(!q.empty()){ a = q.front(); q.pop(); if(map[a.x][a.y]=='E'){ ans = a.step; return ; } for(i = 0;i < 4; i++){ next.x = a.x + dir[i][0]; next.y = a.y + dir[i][1]; if(check(next.x,next.y)) continue; next.step = a.step + 1; vis[next.x][next.y] = true; q.push(next); } } ans = -1; } int main() { int t; cin>>t; while(t--){ cin>>n>>m; for(int i = 0;i < n;i++) scanf("%s",map[i]); for(int i = 0;i < n;i++){ for(int j = 0;j < m;j++){ if(map[i][j]=='S'){ sx = i; sy = j; } } } memset(vis,0,sizeof(vis)); bfs(); cout<<ans<<endl; } return 0; }
相关文章推荐
- 自定义窗体(一)
- 第十九课(二)
- 解决 Android Studio 乱码问题
- 《毛主席诗词全集》150首
- [转] 关于ubuntu的sources.list总结
- 使用STM32CUBEMX生成USB Mass Storage代码,通过SDIO读写TF卡
- GPS经纬度转换屏幕坐标
- 用树莓派搭建你自己的Web服务器,以及一个可以外网访问的Blog
- [转] 停止支持的老版本ubuntu源列表-old-releases
- jQuery性能优化
- 《笨办法学Python》 第33课手记
- 纯CSS实现一个微信logo,需要几个标签?
- 概率论常用公式
- 王楠首次讲述Cocos Creator背后的故事
- <Java设计模式>—简单工厂模式
- 写一个Android输入法02——候选窗、转换
- 笔记本win10关机异常解决
- [POJ 3274]Gold Balanced Lineup[math][sort]
- poj 1061 青蛙的约会
- Android虚拟机打不开解决方法