您的位置:首页 > 其它

POJ 3984 迷宫问题

2016-02-27 19:23 357 查看
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)

又一个搜索题。很久以前就在考虑游戏中的寻路ai该怎么写,这算是最简单的寻路吧。下面代码用的是DFS。

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <map>
#include<queue>
using namespace std;
int n=5,k;
bool isok[6][6];
int res[2][30],temp[2][30];
int minstep=10000;
void dfs(int x,int y,int cnt)
{
temp[0][cnt]=x;
temp[1][cnt]=y;
if(x==4&&y==4)
{
if(cnt<minstep)
{
minstep=cnt;
for(int i=0;i<30;i++)
{
res[0][i]=temp[0][i];
res[1][i]=temp[1][i];
}
}
return;
}
else
{
if(isok[x][y+1])
{
isok[x][y+1]=false;
dfs(x,y+1,cnt+1);
}
if(isok[x+1][y])
{
isok[x+1][y]=false;
dfs(x+1,y,cnt+1);
}
if(isok[x][y-1])
{
isok[x][y+1]=false;
dfs(x,y-1,cnt+1);
}
if(isok[x-1][y])
{
isok[x][y+1]=false;
dfs(x-1,y,cnt+1);
}
isok[x][y]=true;
return;
}
}
int main()
{
for(int i=0;i<n;i++)
{
char c;
for(int j=0;j<n;j++)
{
cin>>c;
if(c=='0')
isok[i][j]=true;
else isok[i][j]=false;
}
}
dfs(0,0,1);
for(int j=1;j<=minstep;j++)
{
cout<<"("<<res[0][j]<<", "<<res[1][j]<<")"<<endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: