POJ 3984 迷宫问题
迷宫问题
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 20612 Accepted: 12062
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 Input0 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
代码1:网上用STL写的
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stack>
#include <queue>
#include <vector>
#include <algorithm>
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
int map[5][5];//地图
int go[4][2]= {{1,0},{-1,0},{0,-1},{0,1}};//四个方向
int pre[10000];//用来寻找父亲节点
bool vis[10][10];//标记数组
struct node
{
int x,y,s;
};//存储坐标信息及当前步数
int bfs(int x,int y)
{
node now,to;//先在的和将要走的
now.x=x,now.y=y,now.s=0;
queue<node>q;//创建队列
vis[x][y]=1;//走过的标记为1
q.push(now);//加入队首
while(!q.empty())
{
now=q.front();
if(now.x==4&&now.y==4)return now.s;//满足条件时返回走过的步数
q.pop();
for(int i=0; i<4; i++)
{
int xx=now.x+go[i][0];
int yy=now.y+go[i][1];
if(xx>=0&&yy>=0&&xx<5&&yy<5&&map[xx][yy]==0&&vis[xx][yy]==0)//判断是否越界
{
vis[xx][yy]=1;//标记走过的
to.x=xx,to.y=yy,to.s=now.s+1;
pre[xx*5+yy]=now.x*5+now.y;//存储坐标,转化成一维形式
q.push(to);
}
}
}
return 0;
}
void myprint(int n)
{
//printf("pre[%d]=(%d)\n",n,pre[n]);
if(n==pre[n])return;
myprint(pre[n]);//寻找父亲节点
printf("(%d, %d)\n",n/5,n%5);
}//回溯打印路径
int main()
{
mem(vis,0);
for(int i=0; i<5; i++)
for(int j=0; j<5; j++)
scanf("%d",&map[i][j]);//读入地图
if(bfs(0,0))
{
printf("(0, 0)\n");//先打印0 0
myprint(4*5+4);//从(4,4)开始回溯
}
else
printf("-1\n");
return 0;
}
代码2:这个容易理解点
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
int maze[5][5];
int dir[4][2] = {0,1,0,-1,1,0,-1,0};
struct node
{
int x;
int y;
int pre;
}arr[105];
void print(int i)
{
if(arr[i].pre!=-1){
print(arr[i].pre);
cout<<"("<<arr[i].x<<","<<" "<<arr[i].y<<")"<<endl;
}
}
void bfs(int xx,int yy)
{
int now = 0,next = 1;
arr[now].x = xx;
arr[now].y = yy;
arr[now].pre = -1;
while(now < next)
{
for(int i=0;i<4;i++)//遍历
{
int m = arr[now].x + dir[i][0];
int n = arr[now].y + dir[i][1];
if(m<0||n<0||m>4||n>4||maze[m][n])//剪枝
continue;
else
{
maze[m][n] = 1;//标记已走过
arr[next].x = m;
arr[next].y = n;
arr[next].pre = now;
next++;
}
if(m==4&&n==4)
print(now);
}
now++;
}
}
int main()
{
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
cin>>maze[i][j];
cout<<"(0, 0)"<<endl;
bfs(0,0);
cout<<"(4, 4)"<<endl;
return 0;
}