您的位置:首页 > 其它

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: