广度优先搜索概念
广搜和深搜都会搜完所有的可能性。广搜有点像水面上的涟漪,还是用迷宫比喻,广搜会先把起点加入队列,然后弹出这个起点,把从这个起点走到的下一个的岔路口或者死路加入队列,然后依次弹出加入,适合做遍历完所有结点找出口或者做求最短出迷宫路径这种题。
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站上嘉持裴老师讲的真的好,跟着他的思路很好理解。