迷宫问题 POJ - 3984 (搜索)
|
迷宫问题
Description 定义一个二维数组:
它表示一个迷宫,其中的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) Source |
题意:从左上角走到右下角,1表示墙壁不可以走,0表示可以走的路,输出最短路的路径。
思路:可以用递归的方法记录路径,比如用pre[i][j].ii,pre[i][j].jj就是i,j的前一点为ii,jj;然后可以用vector来输出路径(vj上面用C++交CE了,好像是储存的时候node{}的问题,用G++交就可以了)
#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> #include<cmath> #include<cstdlib> #include<queue> #include<set> #include<vector> using namespace std; #define INF 0x3f3f3f3f #define eps 1e-10 #define PI acos(-1.0) #define _e exp(1.0) #define ll long long const int maxn=10; struct node { int ii,jj; }; int map[maxn][maxn]; int vis[maxn][maxn]; //标记迷宫 node pre[maxn][maxn]; //记录路径,pre[i][j].ii,pre[i][j].jj就是i,j的前一点为ii,jj; typedef pair<int,int>P; vector<node>a; //记录结果路径 int dx[]={1,0,-1,0}; int dy[]={0,-1,0,1}; int judge(int xx,int yy) { if(xx>=0 && yy>=0 && xx<5 && yy<5 && !vis[xx][yy] && map[xx][yy]==0) return 1; else return 0; } void bfs(int u,int v) { queue<P>que; memset(vis,0,sizeof(vis)); while(!que.empty()) que.pop(); que.push(P(u,v)); vis[u][v]=1; while(que.size()) { P p=que.front();que.pop(); if(p.first==4 && p.second==4) //到达终点 { a.push_back((node){p.first,p.second}); //记录路径 while(p.first || p.second) //直到起点退出循环 { int xx=p.first,yy=p.second; a.push_back((node){pre[xx][yy].ii,pre[xx][yy].jj}); //存入上一点 p.first=pre[xx][yy].ii; p.second=pre[xx][yy].jj; } for(int i=a.size()-1;i>=0;i--) //反向输出 { printf("(%d, %d)\n",a[i].ii,a[i].jj); } return; } for(int i=0;i<4;i++) { int xx=p.first+dx[i]; int yy=p.second+dy[i]; if(judge(xx,yy)) { vis[xx][yy]=1; pre[xx][yy]=(node){p.first,p.second}; //记录好哪一点到的这一点 que.push(P(xx,yy)); } } } } int main() { for(int i=0;i<5;i++) for(int j=0;j<5;j++) scanf("%d",&map[i][j]); bfs(0,0); a.clear(); return 0; }

浙公网安备 33010602011771号