Problem A: 走迷宫问题

Problem A: 走迷宫问题
Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 9 Solved: 3
[Submit][Status][Web Board]
Description
给定一个二维数组 int map[5][5] = {
0 , 1 , 0 , 0 , 0 ,
0 , 1 , 0 , 1 , 0 ,
0 , 0 , 0 , 0 , 0 ,
0 , 1 , 1 , 1 , 0 ,
0 , 0 , 0 , 1 , 0 ,
} ;

Input
输入两个正整数m,n 代表m行,n列的矩阵
输入m*n矩阵元素,它表示一个迷宫,其中“1”表示墙壁,“0”表示可以走的路,只能横着走或者竖着走,不能斜着走

Output
要求编写程序求出从左上角到右下角的最短路径的长度,

Sample Input
5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
Sample Output
8
my answer:

#include<iostream>
#include<queue>
using namespace std;
typedef struct dot{
    int x,y;
    int step;
}dot;
int n,m;
bool in(int x,int y)
{
    if(x>=0&&x<n&&y>=0&&y<m)
    return true;
    else
    return false;
}
int dx[]={1,0,-1,0};
int dy[]={0,1,0,-1};
 
int main()
{
    while(cin>>n>>m){
    int vis[60][60];
    for(int i=0;i!=n;i++){
        for(int j=0;j!=m;j++){
            cin>>vis[i][j];
        }
    }
    dot g1,next;
    int ok=0;
    g1.x=0;
    g1.y=0;
    g1.step=0;
    queue<dot> q;
//    while(!q.empty()) q.pop;
    q.push(g1);
    int count=0;
    while(!q.empty()){
        dot g;
        g=q.front();q.pop();
        for(int k=0;k<=3;k++){
            next.x=g.x+dx[k];
            next.y=g.y+dy[k];
            next.step=g.step+1;
            if(in(next.x,next.y)&&!vis[next.x][next.y]){
                if(next.x==n-1&&next.y==m-1){
                    cout<<next.step<<endl;
                    count++;
                    ok=1;
                    break;
                }
                else{
                    vis[next.x][next.y]=1;
                    q.push(next);
                    count++;
                }
            }
        }
        if(ok)break;
    }
    if(count==0)
      cout<<0<<endl;
}
    return 0;
}

 

转载于:https://www.cnblogs.com/NYNU-ACM/p/4236897.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值