【算法笔记】DAY9_8.2广度优先搜索

广度优先搜索概念

广搜和深搜都会搜完所有的可能性。广搜有点像水面上的涟漪,还是用迷宫比喻,广搜会先把起点加入队列,然后弹出这个起点,把从这个起点走到的下一个的岔路口或者死路加入队列,然后依次弹出加入,适合做遍历完所有结点找出口或者做求最短出迷宫路径这种题。

P1162 填涂颜色

#include<iostream>
using namespace std;
#include<queue>

int n;
int matrix[33][33];
int vis[33][33];
int direction_X[4] = { 1,0,-1,0 };
int direction_Y[4] = { 0,1,0,-1 };

void bfs(int x, int y) {
	
}
int main() {
	cin >> n ;
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= n; j++) {
			cin >> matrix[i][j];
		}
	}
	vis[0][0] = 1;
	queue <int> x;
	queue <int> y;
	x.push(0); y.push(0);
	while (!x.empty()) {
		for (int i = 0; i < 4; i++) {
			int topx = x.front();
			int topy = y.front();
			topx += direction_X[i];
			topy += direction_Y[i];
			if (topx >= 0 && topx <= n + 1 && topy >= 0 && topy <= n + 1
				&& matrix[topx][topy] == 0 && vis[topx][topy] != 1) {
				x.push(topx); y.push(topy);
				vis[topx][topy] = 1;
			}
		}
		x.pop();
		y.pop();
	}
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= n; j++) {
			if (vis[i][j] != 1 && matrix[i][j] == 0)
				matrix[i][j] = 2;
		}
	}
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= n; j++) {
			cout << matrix[i][j]<<' ';
		}
		cout << endl;
	}
	return 0;
}

P1443 马的遍历

#include<iostream>
using namespace std;
#include<queue>
#include<cstring>
#include<iomanip>
int n, m, sx, sy;
int mp[405][405];
int direction_X[8] = { 1,1,2,2,-1,-1,-2,-2 };
int direction_Y[8] = { 2,-2,1,-1,2,-2,1,-1 };

struct Node {
	int x, y, st;
};

int main() {
	cin >> n >> m >> sx >> sy;
	memset(mp, -1, sizeof(mp));
	queue <Node> q;
	Node c = { sx,sy,0 };
	q.push(c);
	mp[sx][sy] = 0;
	while (!q.empty()) {
		for (int i = 0; i < 8; i++) {
			int dx = q.front().x + direction_X[i];
			int dy = q.front().y + direction_Y[i];
			if (dx >= 1 && dx <= n && dy >= 1 && dy <= m && mp[dx][dy] == -1) {
				mp[dx][dy] = q.front().st + 1;
				q.push({ dx, dy, q.front().st + 1 });
			}
		}
		q.pop();
	}

	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			cout << left << setw(5) << mp[i][j];
		}
		cout << endl;
	}
	return 0;
}

ps:b站上嘉持裴老师讲的真的好,跟着他的思路很好理解。

  • 11
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值