迷宫问题 POJ - 3984
定义一个二维数组:
int maze[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,
};
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input
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
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
struct node{
int x;
int y;
}step[10][10];
int n,m;
int e[10][10];
int vist[10][10];
queue<node> q;
int dx[6]={0,0,0,-1,1};
int dy[6]={0,-1,1,0,0};
bool check(int x,int y)//判断是否合法
{
if(vist[x][y]==1||x<0||x>=5||y<0||y>=5||e[x][y]==1) return true;
else return false;
}
void print(node p)//输出路径
{
if(p.x==0&&p.y==0){
printf("(0, 0)\n");
return ;
}
print(step[p.x][p.y]);
printf("(%d, %d)\n",p.x,p.y);
}
void bfs()
{
q.push({0,0});//0 0点开始
vist[0][0]=1;//标记看过
while(!q.empty()){
node cur=q.front();
q.pop();
if(cur.x==4&&cur.y==4){//到达终点
print(cur);
}
for(int i=1;i<=4;i++){
int newx=cur.x+dx[i];//改变xy的方向
int newy=cur.y+dy[i];
if(check(newx,newy)) continue;
q.push({newx,newy});//压入队中
vist[newx][newy]=1;//表示看过
step[newx][newy]=cur;//保存上一个坐标的位置
}
}
}
int main()
{
int i,j;
for(i=0;i<5;i++){
for(j=0;j<5;j++){
scanf("%d",&e[i][j]);
}
}
memset(vist,0,sizeof(vist));
bfs();
}