poj3984迷宫问题

定义一个二维数组:
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)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <cstdio>
#include <iostream>
#include <queue>
//#include <bits/stdc++.h>
#include <cstring>
using namespace std;
int mat[5][5];
int dir[5][2]={{1,0},{0,1},{0,-1},{-1,0}};
struct node{
int x,y,pre;
}point[100];
void dfs(node p)
{
if(p.pre==-1){printf("(%d, %d)\n",p.x,p.y);return;}
dfs(point[p.pre]);
printf("(%d, %d)\n",p.x,p.y);
}
void bfs()
{
int x,y,dx,dy,pre=0,cur=1;
//queue<node> q;
point[0].x=0,point[0].y=0,point[0].pre=-1;
mat[0][0]=1;
while(pre<=cur){
if(point[pre].x==4&&point[pre].y==4){
dfs(point[pre]);
return ;
}
for(int i=0;i<4;++i){
dx=point[pre].x+dir[i][0];
dy=point[pre].y+dir[i][1];
if(dx<0||dx>=5||dy<0||dy>=5||mat[dx][dy])continue;
point[cur].x=dx,point[cur].y=dy,point[cur].pre=pre;
++cur;
}
++pre;
}
}
int main()
{
for(int i=0;i<5;++i)
for(int j=0;j<5;++j)
scanf("%d",&mat[i][j]);
bfs();
return 0;
}

-------------本文结束感谢您的阅读-------------
0%