題目鏈接:http://poj.org/problem?id=3984
題目:
迷宮問題
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 35034 | Accepted: 19912 |
Description
定義一個二維數組:
它表示一個迷宮,其中的1表示牆壁,0表示可以走的路,只能橫着走或豎着走,不能斜着走,要求編程序找出從左上角到右下角的最短路線。
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; }