迷宫问题
| Time Limit: 1000MS |
|
Memory Limit: 65536K |
| Total Submissions: 8089 |
|
Accepted: 4765 |
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)
本题关键在于输出路径,,方法是利用一个father数组记录父节点,再逆向存入新的数组,正向输出。
father[nx*5+ny]=p.first*5+p.second;
a[j++]=father[k];
k=father[k];
这里形成一中环环相扣,最后一个数组是father[24]{4,4}它存储着上一个位置的值x*5+y,而这一个又存储着它的上一个。。。直到k=0{0,0}。
#include
#include
using namespace std; int maze[5][5]; int d[5][5]; const int INF=1000; int father[30]; typedef pair
P; int dx[4]={-1,0,1,0},dy[4]={0,-1,0,1}; void print() { int a[30]; int j=0,k=24; while(k!=0) { a[j++]=father[k]; k=father[k]; } for(int i=j-1;i>=0;i--) cout<<"("<
que; que.push(P(0,0)); d[0][0]=0; while(que.size()) { P p = que.front(); que.pop(); if(p.first == 4&&p.second == 4) { print(); break; } for(int i=0;i<4;i++){ int nx=p.first+dx[i],ny=p.second+dy[i]; if(0<=nx&&nx<5&&0<=ny&&ny<5&&maze[nx][ny]==0&&d[nx][ny]==INF) { que.push(P(nx,ny)); father[nx*5+ny]=p.first*5+p.second; d[nx][ny]=d[p.first][p.second]+1; } } } // return d[4][4]; 返回最短路径数 } int main() { int i,j; for(i=0;i<5;i++) for(j=0;j<5;j++) cin>>maze[i][j]; bfs(0,0); return 0; }
这里通过一个二维数组记录(d[nx][ny]=d[p.first][p.second]+1;)到达每个位置所需行走的最短长度,,可以返回最短路径值,但本题不作要求。