poj3894
bfs+记录路径
迷宫问题
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 5385 Accepted: 3064
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<stdio.h>
#include<iostream>
#include<string>
#include<string.h>
#include<algorithm>
#include<math.h>
#include<map>
#include<queue>
#include<vector>
using namespace std;
struct point
{
int x,y,pre;
} que[1000];
int dir[][2]= {{0,1},{0,-1},{1,0},{-1,0}};
int mymap[100][100];
int vis[100][100];
int front,rear;
int n,k;
void print(int s)
{
if(s!=-1)
{
print(que[s].pre);
printf("(%d,%d)\n",que[s].x,que[s].y);
}
}
void bfs()
{
int i,j,tmpx,tmpy;
point tmp1;
tmp1.x=0;
tmp1.y=0;
tmp1.pre=-1;
front=rear=0;
vis[0][0]=1;
que[rear++]=tmp1;
while(rear>front)
{
tmp1=que[front];
for(i=0; i<4; i++)
{
tmpx=tmp1.x+dir[i][0];
tmpy=tmp1.y+dir[i][1];
if(tmpx>=0&&tmpx<n&&tmpy>=0&&tmpy<n&&!vis[tmpx][tmpy]&&mymap[tmpx][tmpy]==0)
{
vis[tmpx][tmpy]=1;
tmp1.x=tmpx;
tmp1.y=tmpy;
tmp1.pre=front;
que[rear++]=tmp1;
}
if(vis[4][4])
{
printf("*%d %d*\n",front,rear);
print(front);
return;
}
}
front++;
}
}
int main()
{
//freopen("in.txt","r",stdin);
int i,j;
n=5;
for(i=0; i<n; i++)
for(j=0; j<n; j++)
scanf("%d",&mymap[i][j]);
// cout<<"(0, 0)"<<endl;
bfs();
printf("(%d,%d)\n", )
// cout<<"("<<n-1<<", "<<n-1<<")"<<endl;
// for(i=0; i<n; i++)
// {
// for(j=0; j<N; j++)
// {
// printf("%d ",map[i][j]);
//
// }
// puts("");
// }
return 0;
}
/*
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 1 0 1 0
*/