题解 广搜记录路径 POJ 3984
题意:定义一个二维数组:
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表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
做法:1 广搜寻找最短路径;
2 建立数组用于记录路径 从结果开始查找父亲节点;
附:坐标压缩法
顾名思义,就是将本来是用两个数来表示的坐标(x, y),用一个数来表示。
为什么?简便呗!
第i行第j列的格子编号为i*m+j
反之,编号为u的节点,其行号和列号分别为u / m; u % m;
代码:
#include <iostream> #include <queue> #include <stack> using namespace std; int i,j,m,re; int num[5][5]; int loc[5][5]; queue<int>que; stack <int > sta; bool inbound(int x) { if (x >=0) if (x < 5) return true; else return false; else return false; } void bfs(int x,int y) { m=que.size(); for(i=0;i<m;i++) { if(inbound(x-1)&&inbound(y)&&num[x-1][y]==0&&loc[x][y]==0) {que.push(5*(x-1)+y);num[x-1][y]=num[x][y]+1;} if(inbound(x)&&inbound(y-1)&&num[x][y-1]==0&&loc[x][y]==0) {que.push(5*x+y-1);num[x][y-1]=num[x][y]+1;} if(inbound(x)&&inbound(y+1)&&num[x][y+1]==0&&loc[x][y]==0) {que.push(5*x+y+1);num[x][y+1]=num[x][y]+1;} if(inbound(x+1)&&inbound(y)&&num[x+1][y]==0&&loc[x][y]==0) {que.push(5*(x+1)+y);num[x+1][y]=num[x][y]+1;} } que.pop(); } void print(int x, int y) { if(inbound(x-1)&&inbound(y)&&num[x-1][y]==num[x][y]-1&&loc[x-1][y]==0) {re--;sta.push(5*(x-1)+y);print(x-1,y);} else if(inbound(x)&&inbound(y-1)&&num[x][y-1]==num[x][y]-1&&loc[x][y-1]==0) {re--;sta.push(5*x+y-1);print( x, y-1);} else if(inbound(x)&&inbound(y+1)&&num[x][y+1]==num[x][y]-1&&loc[x][y+1]==0) {re--;sta.push(5*x+y+1);print(x, y+1);} else if(inbound(x+1)&&inbound(y)&&num[x+1][y]==num[x][y]-1&&loc[x+1][y]==0) {re--;sta.push(5*(x+1)+y);print(x+1, y);} } int main() { for(i=0;i<5;i++) for(j=0;j<5;j++) num[i][j]=0,cin>>loc[i][j]; que.push(0); while(num[4][4]==0)bfs(que.front()/5,que.front()%5); re=num[4][4]; /*cout<<num[4][4]<<endl;*/ print(4,4); cout<<"(0, 0)"<<endl; while(sta.size()!=0) { cout<<"("<<sta.top()/5<<", "<<sta.top()%5<<")"<<endl; sta.pop(); } cout<<"(4, 4)"<<endl; return 0; }