迷宫问题Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u
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,
};
Input
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记录路径问题,方法依然是让每个节点记录从起点到达自己的路径,这里用的string,因为在拼接的时候很方便而且节点的坐标不可能超过9。
#include <iostream> #include <queue> #include <string> #include <memory.h> using namespace std; int Map[5][5];//地图 int visit[5][5];//BFS中最重要的visit数组 int dirr[]={-1,1,0,0};//方向数组 int dirc[]={0,0,-1,1}; struct P { int r,c; string path;//每个节点都单独记录路径 P(int _r,int _c,string _path) { r=_r; c=_c; path=_path; } P(){} }; string bfs()//返回路径的BFS { queue<P> q; string t;//路径 int r,c,i; t="(0, 0)\n"; q.push(P(0,0,t)); visit[0][0]=1; while(!q.empty()) { P temp=q.front(); q.pop(); if(temp.r==4&&temp.c==4)//到达终点,返回路径 { return temp.path; } for(i=0;i<4;i++)//四向搜索 { r=temp.r+dirr[i]; c=temp.c+dirc[i]; if(r>=0&&r<5&&c>=0&&c<5&&visit[r][c]==0&&Map[r][c]==0) { visit[r][c]=1; t=temp.path;//更新路径 t+="("; t+=(char)('0'+r); t+=", "; t+=(char)('0'+c); t+=")\n"; q.push(P(r,c,t)); } } } } int main() { int i,j; for(i=0;i<5;i++) { for(j=0;j<5;j++) { cin>>Map[i][j]; } } memset(visit,0,sizeof(visit)); string Path=bfs(); cout<<Path<<endl; return 0; }