您的位置:首页 > 其它

POJ3984(迷宫问题)

2016-07-13 21:17 363 查看
迷宫问题

Time Limit: 1000MSMemory Limit: 65536K
Total Submissions: 15154Accepted: 9030
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 <string.h>
using namespace std;
const int MAXN=1000005;
struct Node{
int y,x,pre;
Node(){}
Node(int cy,int cx,int cpre)
{
y=cy;
x=cx;
pre=cpre;
}
}que[MAXN];
int front,rear;
int mz[5][5];
int vis[5][5];
int dy[4]={0,1,0,-1};
int dx[4]={1,0,-1,0};
void print(int id)
{
Node now=que[id];
if(now.pre==-1)
{
cout<<"("<<now.y<<", "<<now.x<<")"<<endl;
return ;
}
print(now.pre);
cout<<"("<<now.y<<", "<<now.x<<")"<<endl;
}
void bfs()
{
memset(vis,0,sizeof(vis));
front=rear=0;
que[rear++]=Node(0,0,-1);
vis[0][0]=1;
while(front!=rear)
{
Node now=que[front++];
if(now.y==4&&now.x==4)
{
print(front-1);
return ;
}
for(int i=0;i<4;i++)
{
int ny=now.y+dy[i];
int nx=now.x+dx[i];
if(0<=ny&&ny<5&&0<=nx&&nx<5&&!vis[ny][nx]&&mz[ny][nx]==0)
{
que[rear++]=Node(ny,nx,front-1);
vis[ny][nx]=1;
}
}
}

}
int main()
{
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
cin>>mz[i][j];
bfs();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: