原题链接:FZU—2285
题目描述:
描述:洪尼玛今天准备去寻宝,在一个n*n (n行, n列)的迷宫中,存在着一个入口、一些墙壁以及一个宝藏。由于迷宫是四连通的,即在迷宫中的一个位置,只能走到与它直接相邻的其他四个位置(上、下、左、右)。现洪尼玛在迷宫的入口处,问他最少需要走几步才能拿到宝藏?若永远无法拿到宝藏,则输出-1。
输入:多组测试数据。每组数据输入第一行为正整数n,表示迷宫大小。接下来n行,每行包括n个字符,其中字符’.‘表示该位置为空地,字符’#'表示该位置为墙壁,字符’S’表示该位置为入口,字符’E’表示该位置为宝藏,输入数据中只有这四种字符,并且’S’和’E’仅出现一次。
n≤1000
输出:输出拿到宝藏最少需要走的步数,若永远无法拿到宝藏,则输出-1。
题目解法:模板题,广度优先搜索。
题目代码:
#include<stdio.h>
#include<queue>
#include<math.h>
#include<string.h>
using namespace std;
char map[1000][1001];
int suit[1000][1001];
int n;
struct node
{
int x,y;
int step;
};
int check(int x,int y)
{
if(x >= n || y >= n || map[x][y] == '#'||x<0||y<0||suit[x][y]==1)
return 0;
return 1;
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
int i,T=0;
for(i=0;i<n;i++)
scanf("%s",map[i]);
memset(suit,0,sizeof(suit));
struct node a,next;
queue<node> Q;
a.x=0,a.y=0;
a.step=0;
Q.push(a);
while(!Q.empty())
{
a=Q.front();
Q.pop();
if(map[a.x][a.y]=='E')
{
printf("%d\n",a.step);
T=1;
break;
}
next.x=a.x-1;
next.y=a.y;
if(check(next.x,next.y))
{
next.step=a.step+1;
suit[next.x][next.y]=1;
Q.push(next);
}
next.x=a.x+1;
next.y=a.y;
if(check(next.x,next.y))
{
next.step=a.step+1;
suit[next.x][next.y]=1;
Q.push(next);
}
next.x=a.x;
next.y=a.y+1;
if(check(next.x,next.y))
{
next.step=a.step+1;
suit[next.x][next.y]=1;
Q.push(next);
}
next.x=a.x;
next.y=a.y-1;
if(check(next.x,next.y))
{
next.step=a.step+1;
suit[next.x][next.y]=1;
Q.push(next);
}
}
if(T==0)
printf("-1\n");
}
return 0;
}
欢迎留言哦!