您的位置:首页 > 其它

BFS------迷宫

2017-05-22 17:48 127 查看
走迷宫

Time Limit : 3000/1000ms (Java/Other) Memory Limit : 65535/32768K (Java/Other)

Total Submission(s) : 92 Accepted Submission(s) : 10

Font: Times New Roman | Verdana | Georgia

Font Size: ← →

Problem Description

Rico的芝士被Dave随手丢到一个有n*m个格子的迷宫里去了,在这个迷宫里只能上下左右走,每走一格都要花去1分钟。现在Rico要去找到它以便后边的剧情不被改变,而他想提前知道拿回芝士要花多长时间。

Input

输入数据有多组,以“0 0”结束输入。

每一组的第1行有2个整数n,m(1

2 2
##
.c
3 3
###
#c#
..#
0 0


Sample Output

4
6


Author

njtechliubin

#include<stdio.h>
#include<iostream>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<queue>
using namespace std;

const int inf = 1000000;
const int maxm = 110;
const int maxn = 110;
int sx,sy;
int gx,gy;
int m,n;
typedef pair<int,int> P;
int dis[maxm][maxn];
int dx[4] = {1,0,-1,0};
int dy[4] = {0,1,0,-1};
char maze[maxm][maxn+1];

int bfs(){
queue<P> que;
for(int i = 1; i <= m; i++){
for(int j = 1; j <= n; j++){
dis[i][j] = inf;
}
}
que.push(P(sx,sy));
dis[sx][sy] = 0;
while(que.size()){
P p = que.front();
que.pop();
if(p.first == gx && p.second == gy) break;
for(int i = 0; i < 4; i++){
int nx = p.first + dx[i];
int ny = p.second + dy[i];
if(nx>=1 && nx <= m && ny >= 1 && ny <= n &&
maze[nx][ny] != '#' && dis[nx][ny] == inf){
que.push(P(nx,ny));
dis[nx][ny] = dis[p.first][p.second] + 1;
}
}
}
return dis[gx][gy];
}

int main(void)
{
while(scanf("%d%d",&m,&n)){
if(m==0 && n==0) break;
for(int i = 1; i <= m; i++){
for(int j = 1; j <= n; j++){
scanf(" %c",&maze[i][j]);
if(maze[i][j] == 'c'){
gx = i;
gy = j;
}
}
}
sx = m;
sy = 1;

int res = bfs();
printf("%d\n",(res+1)*2);

}

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