您的位置:首页 > 其它

Poj 3752:走迷宫

2016-05-23 22:13 218 查看

3752:走迷宫

查看
提交
统计
提示
提问

总时间限制: 1000ms 内存限制: 65536kB

描述一个迷宫由R行C列格子组成,有的格子里有障碍物,不能走;有的格子是空地,可以走。

给定一个迷宫,求从左上角走到右下角最少需要走多少步(数据保证一定能走到)。只能在水平方向或垂直方向走,不能斜着走。

输入第一行是两个整数,R和C,代表迷宫的长和宽。( 1<= R,C <= 40)

接下来是R行,每行C个字符,代表整个迷宫。

空地格子用'.'表示,有障碍物的格子用'#'表示。

迷宫左上角和右下角都是'.'。
输出输出从左上角走到右下角至少要经过多少步(即至少要经过多少个空地格子)。计算步数要包括起点和终点。
样例输入
5 5
..###
#....
#.#.#
#.#.#
#.#..


样例输出

9

Bfs:

#include "iostream"

#include "string.h"
#include "stdio.h"
#include "queue"
using namespace std;
#define Max 50
int Length,Width;
char Map[Max][Max];
bool Judge[Max][Max]={0};
int Move[4][2]={0,1,1,0,0,-1,-1,0};
struct Node
{
int x,y,step;
};

int Bfs()
{
queue<Node> Q;
while(!Q.empty())
Q.pop();

Node one;
one.x=1;one.y=1;one.step=1;
Judge[1][1]=true;
Q.push(one);
while(!Q.empty())
{
Node Pos=Q.front(); Q.pop();
int dx,dy,i;
for(i=0;i<4;i++)
{
dx=Pos.x+Move[i][0];
dy=Pos.y+Move[i][1];

if(dx>=1 && dx<=Width && dy>=1 && dy<=Length && Map[dx][dy]=='.'&& !Judge[dx][dy])
{
if(dx==Width && dy==Length)
{
return Pos.step+1;
}
Node item;
item.x=dx; item.y=dy; item.step=Pos.step+1;
Judge[dx][dy]=true;
Q.push(item);
}
}
}
}
int main()
{

//freopen("1.txt","r",stdin);
while(cin>>Width>>Length)
{

int i,j;
memset(Judge,false,sizeof(Judge));
for(i=1;i<=Width;i++)
for(j=1;j<=Length;j++)
{
cin>>Map[i][j];
}

cout<<Bfs()<<endl;

}

return 0;
}


Dfs:

#include "iostream"
#include "vector"
#include "string.h"
#include "stdio.h"
using namespace std;
#define MIN(a,b)(a<b?a:b)
#define Max 50
vector<int> Walk;
char Map[Max][Max];
bool Judge[Max][Max];
int Move[4][2]={0,1,1,0,0,-1,-1,0};
int M,N;
void Dfs(int x,int y,int count)
{
if(x==N && y==M)
{
Walk.push_back(count);
return ;
}
int i;
for(i=0;i<4;i++)
{
int dx,dy;
dx=x+Move[i][0];
dy=y+Move[i][1];
char str=Map[dx][dy];

if(!Judge[dx][dy] && Map[dx][dy]=='.'  && dx>=1 && dx<=N && dy>=1 && dy<=M  )
{
Judge[dx][dy]=true;
Dfs(dx,dy,count+1);
Judge[dx][dy]=false;
}
}
}
int main()
{
//freopen("1.txt","r",stdin);
while( cin>>N>>M && M!=0 &&N!=0)//R C
{

Walk.clear();
memset(Judge,false,sizeof(Judge));
int i,j;
for(i=1;i<=N;i++)
for(j=1;j<=M;j++)
cin>>Map[i][j];
Dfs(1,1,1);
int ans=1<<30;
for(i=0;i<Walk.size();i++)
{
ans=MIN(ans,Walk[i]);
}
cout<<ans<<endl;

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: