您的位置:首页 > 其它

poj迷宫问题(bfs路径输出)

2015-08-22 15:23 274 查看
题目地址:http://poj.org/problem?id=3984
迷宫问题

Time Limit: 1000MSMemory Limit: 65536K
Total Submissions: 11638Accepted: 6967
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)

Source

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
int map[10][10];
int visit[10][10];
int dir[4][2]= {0,1,0,-1,1,0,-1,0};
struct nodes
{
int x,y;
};
nodes node1,node2,pre[15][15];
void bfs()
{
queue<nodes> q;
while(!q.empty())
q.pop();
node1.x=0;
node1.y=0;
visit[0][0]=1;
pre[0][0].x=0;
pre[0][0].y=0;
q.push(node1);
while(!q.empty())
{
node1=q.front();
q.pop();
if(node1.x==4&&node1.y==4)
{
break;
}
for(int i=0; i<4; i++)
{
node2.x=node1.x+dir[i][0];
node2.y=node1.y+dir[i][1];
if(node2.x>=0&&node2.x<5&&node2.y>=0&&node2.y<5&&!map[node2.x][node2.y]&&visit[node2.x][node2.y]==0)
{
visit[node2.x][node2.y]=visit[node1.x][node1.y]+1;
pre[node2.x][node2.y].x=node1.x;
pre[node2.x][node2.y].y=node1.y;
q.push(node2);

}
}
}
}
/*
这样写如果第一个方向找的路不对就会出错
void print(int x,int y)
{
if(x==0&&y==0)
{
printf("(0, 0)\n");
return ;
}
for(int i=0; i<4; i++)
{
int xx=x+dir[i][0];
int yy=y+dir[i][1];
if(xx>=0&&xx<=4&&yy>=0&&yy<=4&&visit[xx][yy]==visit[x][y]-1)
{
print(xx,yy);
printf("(%d, %d)\n",x,y);
}
}
}
*/
void print(int x,int y)
{
if(x==0&&y==0)
{
printf("(0, 0)\n");
return ;
}
print(pre[x][y].x,pre[x][y].y);
printf("(%d, %d)\n",x,y);
}
int main()
{
for(int i=0; i<5; i++)

{
for(int j=0; j<5; j++)
{
scanf("%d",&map[i][j]);
}
}
memset(visit,0,sizeof(visit));
bfs();
print(4,4);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: