POJ - 3984迷宫问题(最短路径输出)


题目链接:http://poj.org/problem?id=3984

题目:

迷宫问题
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 35034   Accepted: 19912

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可以很简单求出最短路径的值,但是又怎样输出它的最短路径呢?我们可以开个node类型的二维数组pre[x][y],记录每个节点的前驱顶点是哪个顶点。因为每个节点的前驱节点是唯一的,只会是最快到达它的那个顶点,而每个节点的后继节点却不唯一,它可能可以朝各个方向走,所以记录它的前驱节点是可行的。然后就是输出问题,我们需要递归逆序输出就可以了。
附上代码:
 #include<iostream> #include<cstdio> #include<cstring> #include<queue>
using namespace std; int mp[5][5],vis[5][5]; int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}}; struct node{ int x,y; }; node pre[10][10]; void BFS() { queue<node> que; node str; str.x=str.y=0; que.push(str); vis[0][0]=1; while(!que.empty()) { node now=que.front(); que.pop(); if(now.x==4&&now.y==4) return; for(int i=0;i<4;i++) { node next; next.x=now.x+dir[i][0]; next.y=now.y+dir[i][1]; if(next.x>=0&&next.x<5&&next.y>=0&&next.y<5&&!mp[next.x][next.y]&&!vis[next.x][next.y]) { vis[next.x][next.y]=1; que.push(next); pre[next.x][next.y]=now; } } } } void print(node cur) { if(cur.x==0&&cur.y==0) { printf("(0, 0)\n"); return; } print(pre[cur.x][cur.y]); //逆序输出
    printf("(%d, %d)\n",cur.x,cur.y); } int main() { for(int i=0;i<5;i++) for(int j=0;j<5;j++) scanf("%d",&mp[i][j]); BFS(); node ed; ed.x=ed.y=4; print(ed); return 0; }

 




免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM