【题目描述】
定义一个二维数组:
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表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
【输入】
一个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
【样例输出】
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
题目链接:https://cn.vjudge.net/problem/POJ-3984
用t数组存下全部过程,用*pre还原路径
代码如下:
#include <iostream>
#include <queue>
#include <stack>
#include <cstring>
using namespace std;
static const int MAXN=5;
static const int dx[]={0,0,1,-1},dy[]={1,-1,0,0};
int mp[MAXN+2][MAXN+2];
bool vis[MAXN+2][MAXN+2];
struct Node{
int x,y;
int step;
Node *pre;
};
void bfs(Node node)
{
queue<Node> Q;
Q.push(node);
vis[node.x][node.y]=true;
int cnt=-1;
Node t[30];
while(!Q.empty())
{
cnt++;
t[cnt]=Q.front();
Q.pop();
for(int i=0;i<4;i++)
{
Node next;
next.x=t[cnt].x+dx[i];
next.y=t[cnt].y+dy[i];
next.step=t[cnt].step+1;
if(0<=next.x && next.x<5 && 0<=next.y && next.y<5 && mp[next.x][next.y]==0 && !vis[next.x][next.y])
{
vis[next.x][next.y]=true;
next.pre=&t[cnt];
if(next.x==4 && next.y==4)
{
stack<Node> S;
while(next.pre)
{
S.push(next);
next=*(next.pre);
}
cout<<"(0, 0)"<<endl;
while(!S.empty())
{
Node temp=S.top();
S.pop();
cout<<"("<<temp.x<<", "<<temp.y<<")"<<endl;
}
return;
}
Q.push(next);
}
}
}
}
int main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(0),cout.tie(0);
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
cin>>mp[i][j];
memset(vis,false,sizeof(vis));
bfs(Node{0,0,0,NULL});
return 0;
}