您的位置:首页 > 其它

POJ 3984 迷宫问题

2016-04-02 09:30 288 查看
迷宫问题

Time Limit: 1000MSMemory Limit: 65536K
Total Submissions: 13710Accepted: 8192
Description

定义一个二维数组:

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)


用BFS求最短路径,记录每一个状态之前的状态,输出路径即可

#include <cstdio>
#include <cstring>

using namespace std;

struct cam
{
int x;
int y;
}list[100];

int map[5][5];
int vis[5][5];
int pre[100];    //记录每一个状态的前一个状态
int dir[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};

int go(int x, int y)
{
if (x >= 0 && x < 5 && y >= 0 && y < 5 && map[x][y] == 0)
return 1;
return 0;
}

void print(int x)
{
int t;
t = pre[x];
if (t == 0){
printf("(0, 0)\n");
printf("(%d, %d)\n", list[x].x, list[x].y);
return;
}
else
print(t);
printf("(%d, %d)\n", list[x].x, list[x].y);
}

void bfs()
{
int x, y, xx, yy;
int head = 0, tail = 1;
memset(vis, 0, sizeof(vis));
list[0].x = 0;
list[0].y = 0;
pre[0] = -1;
while (head < tail){
x = list[head].x;
y = list[head].y;
if (x == 4 && y == 4){
print(head);
return;
}
for (int i = 0; i < 4; i++){
xx = x + dir[i][0];
yy = y + dir[i][1];
if (!vis[xx][yy] && go(xx, yy)){
vis[xx][yy] = 1;
list[tail].x = xx;
list[tail].y = yy;
pre[tail] = head;
tail++;
}
}
head++;
}
return;
}

int main()
{
for (int i = 0; i < 5; i++){
for (int j = 0; j < 5; j++){
scanf("%d", &map[i][j]);
}
}
bfs();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: