bfs+路径保存
POJ3984
bfs+路径保存基本模板题吧,用个结构体数组保存一下路径,没啥好说的。
题目
迷宫问题
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 42000 Accepted: 23287
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)
下面是源代码
#include<iostream>
#include <queue>
#include <cstring>
using namespace std;
typedef struct nodee
{
int x;
int y;
int step;
}node;
int sz[2][4] = {0,1,0,-1,1,0,-1,0};
int mapp[6][6];
int flag[6][6];
node pp[100][100];
node dd[35];
queue<node> x;
int bfs(node v)
{
int i;
node t,te;
x.push(v);
flag[0][0]=1;
while(!x.empty())
{
te = x.front();
x.pop();
for(i=0;i<4;i++)
{
t.x = te.x+sz[0][i];
t.y = te.y+sz[1][i];
t.step = te.step;
if(t.x>=0&&t.x<5&&t.y>=0&&t.y<5&&flag[t.x][t.y]==0&&mapp[t.x][t.y]==0)
{
flag[t.x][t.y]=1;
pp[t.x][t.y].x=te.x;
pp[t.x][t.y].y=te.y;
t.step+=1;
if(t.x==4&&t.y==4)
return t.step;
x.push(t);
}
}
}
return 0;
}
void putmap()
{
int k=4,kk=4,k1;
int t=0;
while(1)
{
if(pp[k][kk].x==0&&pp[k][kk].y==0)break;
dd[t].x=pp[k][kk].x;
dd[t].y=pp[k][kk].y;
t++;
k1 = k;
k = pp[k][kk].x;
kk = pp[k1][kk].y;
}
while(t!=-1)
{
cout<<"("<<dd[t].x<<", "<<dd[t].y<<")"<<endl;
t--;
}
cout<<"("<<4<<", "<<4<<")"<<endl;
}
int main()
{
memset(flag,0,sizeof(flag));
int n,i,j;
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
cin>>mapp[i][j];
}
node st;
st.x=0;st.y=0;st.step=0;
bfs(st);
putmap();
return 0;
}