ybtoj·走迷宫【BFS】

Description–

高效进阶「基础算法」第5章 广度搜索课堂过关 例题1


解题思路–

暴搜ヽ(o_ _)o


代码–

#include <iostream>
#include <cstdio>
#include <queue>

using namespace std;

const int f[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; 
int n, ans, k[5], b[1005][1005];
bool a[1005][1005];
char c;

struct hll
{
	int x, y;
};

queue <hll> q;

void bfs()
{
	while (!q.empty())
	{
		hll u = q.front();
		q.pop();
		for (int i = 0; i <= 3; ++i)
		{
			int xx = u.x + f[i][0];
			int yy = u.y + f[i][1];
			if (xx > n || yy > n || xx <= 0 || yy <= 0) continue;
			if (a[xx][yy] || b[xx][yy]) continue;
			q.push((hll){xx, yy}),  b[xx][yy] = b[u.x][u.y] + 1;
			if (xx == k[3] && yy == k[4])
			{
				printf("%d", b[xx][yy] - 1);
				return ;
			}
		}
	}
}

int main()
{
	scanf("%d", &n), ans = n * n;
	for (int i = 1; i <= n; ++i)
	{
		for (int j = 1; j <= n; ++j)
		{
			c = getchar();
			while (c != '1' && c != '0')
			  c = getchar();
			a[i][j] = c - '0';
		}
    }
	scanf("%d%d%d%d", &k[1], &k[2], &k[3], &k[4]);
	q.push((hll){k[1], k[2]});
	b[k[1]][k[2]] = 1, bfs
	();
	
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值