BFS一般通过队列实现
例题:
给出一个m x n的矩阵,矩阵中的元素为0或1。称位置(x,y)与其上下左右四个位置(x, y + 1)、(x, y - 1)、(x + 1, y)、(x - 1, y)是相邻的。如果矩阵中有若干个1是相邻的(不必两两相邻),那么称这些1构成了一个“块”。求给定的矩阵中“块”的个数
广搜方案:
对每一次遇到的1,bfs其相邻区域,标记上。ans+1。
Code:
#include <bits/stdc++.h>
using namespace std;
struct node{
int x, y;
}a; //结构体的存在很关键,它使得坐标可以进队列。从而进行广搜。
int Matrix[30][30];
bool flag[30][30];
int m, n, ans = 0;
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, 1, -1};
bool judge(int x, int y) {
if (x < 0 || x >= m || y < 0 || y >= n)
return false;
if (Matrix[x][y] == 0 || flag[x][y] == true)
return false;
return true;
}
void bfs(int x, int y) {
queue<node> Q;
a.x = x;
a.y = y;
Q.push(a); //循环的初始化。
flag[x][y] = true;
while (!Q.empty()) {
node temp = Q.front();
Q.pop();
int newx, newy;
for (int i = 0; i < 4; i++) {
newx = temp.x + dx[i];
newy = temp.y + dy[i];
if (judge(newx, newy)) {
a.x = newx, a.y = newy;
Q.push(a);
flag[newx][newy] = true; //因为不是递归,所以要在此修改为访问过。
}
}
}
}
int main () {
freopen("./code/in.txt", "r", stdin);
cin >> m >> n;
for (int i = 0; i < m;i++) {
for (int j = 0; j < n; j++) {
cin >> Matrix[i][j];
}
}
memset(flag, false, sizeof(flag));
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (Matrix[i][j] == 1 && flag[i][j] == false) {
ans++;
bfs(i, j);
}
}
}
cout << ans;
}
input
6 7
0 1 1 1 0 0 1
0 0 1 0 0 0 0
0 0 0 0 1 0 0
0 0 0 1 1 1 0
1 1 1 0 1 0 0
1 1 1 1 0 0 0
output
4
例题:
给定一个n * m
大小的迷宫,其中 *
表示不可通过的墙壁,而.
代表平地,S
表示起点, T
表示终点。移动过程中,如果当前位置是(x, y)
(下标从0开始),且每次只能前往上下左右四个位置(x, y + 1)、(x, y - 1)、(x + 1, y)、(x - 1, y)的平地,求从起点到达终点T的最小步数。
广搜方案:
一直搜索,直到终点。因为是广搜,所以一定是最快到达终点的。
Code:
#include <bits/stdc++.h>
using namespace std;
struct node {
int x, y, step;
node() {
step = 0;
}
} a, temp;
char tu[10][10];
int m, n, s_x, s_y, e_x, e_y, newx, newy;
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};
bool flag[10][10] = {false};
bool judge(int x, int y) {
if (x < 0 || x >= m || y < 0 || y >= n)
return false;
if (tu[x][y] == '*' || flag[x][y])
return false;
return true;
}
int bfs() {
queue<node> Q;
a.x = s_x, a.y = s_y;
Q.push(a);
flag[s_x][s_y] = true;
while (!Q.empty()) {
temp = Q.front();
Q.pop();
if (temp.x == e_x && temp.y == e_y)
return temp.step;
for (int i = 0; i < 4; i++) {
newx = temp.x + dx[i];
newy = temp.y + dy[i];
if (judge(newx, newy)) {
a.x = newx, a.y = newy;
a.step = temp.step + 1; //注意从上一个点的step + 1;
Q.push(a);
flag[newx][newy] = true;
}
}
}
return -1;
}
int main()
{
scanf("%d%d", &m, &n);
scanf("%d%d%d%d", &s_x, &s_y, &e_x, &e_y);
getchar();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
scanf("%c", &tu[i][j]);
}
getchar();
}
cout << bfs();
}
input
5 5
2 2 4 3
.....
.*.*.
.*S*.
.***.
...T*
output
11