Problem A: 走迷宫问题

2022-10-22,

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>=&&x<n&&y>=&&y<m)
return true;
else
return false;
}
int dx[]={,,-,};
int dy[]={,,,-}; int main()
{
while(cin>>n>>m){
int vis[][];
for(int i=;i!=n;i++){
for(int j=;j!=m;j++){
cin>>vis[i][j];
}
}
dot g1,next;
int ok=;
g1.x=;
g1.y=;
g1.step=;
queue<dot> q;
// while(!q.empty()) q.pop;
q.push(g1);
int count=;
while(!q.empty()){
dot g;
g=q.front();q.pop();
for(int k=;k<=;k++){
next.x=g.x+dx[k];
next.y=g.y+dy[k];
next.step=g.step+;
if(in(next.x,next.y)&&!vis[next.x][next.y]){
if(next.x==n-&&next.y==m-){
cout<<next.step<<endl;
count++;
ok=;
break;
}
else{
vis[next.x][next.y]=;
q.push(next);
count++;
}
}
}
if(ok)break;
}
if(count==)
cout<<<<endl;
}
return ;
}

Problem A: 走迷宫问题的相关教程结束。

《Problem A: 走迷宫问题.doc》

下载本文的Word格式文档,以方便收藏与打印。