BFS------迷宫

走迷宫

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);

    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值