Q - 迷宫寻宝

洪尼玛今天准备去寻宝,在一个n*n (n行, n列)的迷宫中,存在着一个入口、一些墙壁以及一个宝藏。由于迷宫是四连通的,即在迷宫中的一个位置,只能走到与它直接相邻的其他四个位置(上、下、左、右)。现洪尼玛在迷宫的入口处,问他最少需要走几步才能拿到宝藏?若永远无法拿到宝藏,则输出-1。

Input
多组测试数据。

每组数据输入第一行为正整数n,表示迷宫大小。

接下来n行,每行包括n个字符,其中字符’.‘表示该位置为空地,字符’#'表示该位置为墙壁,字符’S’表示该位置为入口,字符’E’表示该位置为宝藏,输入数据中只有这四种字符,并且’S’和’E’仅出现一次。

n≤1000

Output
输出拿到宝藏最少需要走的步数,若永远无法拿到宝藏,则输出-1。

#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<mem.h>
#include<queue>
using namespace std;
#define ll long long
const int inf = 0x3f3f3f3f;
char g[1010][1010];
bool vis[1010][1010];
int a[4] = {0,0,1,-1};
int b[4] = {1,-1,0,0};
struct node{
	int x,y,step;
};
queue<node>q;
int n,x,y,ex,ey,ans;
void dfs(int x,int y)
{
	node now,next;
	now.x = x,now.y = y,now.step = 0;
	q.push(now);
	while(!q.empty())
	{
		now = q.front();
		q.pop();
		for(int i = 0; i <4; i++)
		{
			next.x = now.x + a[i];
			next.y = now.y + b[i];
			next.step = now.step + 1;
			if(next.x <= n && next.x > 0 && next.y > 0 && next.y <= n && !vis[next.x][next.y] && g[next.x][next.y] != '#')
			{
				vis[next.x][next.y] = true;
				q.push(next);
			}
			if(g[next.x][next.y] == 'E')
			{
				ans = min(ans,next.step);
			}
		}
	}
}
int main()
{
	
	while(~scanf("%d",&n))
	{
		ans = inf;
		memset(vis,false,sizeof(vis));
		for(int i = 1; i <= n; i++)
		{
			for(int j = 1; j <= n; j++)
			{
				scanf(" %c",&g[i][j]);
				if(g[i][j] == 'S')
				{
					x = i,y = j;
				}
			}
		}
		dfs(x,y);
		if(ans != inf)
		printf("%d\n",ans);
		else
		printf("-1\n");
	}
	
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值