题目传送门
一、广度优先搜索解法
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
char a[N][N]; //地图
//坐标结构体
struct coord {
int x, y;
};
int n, m;
int cnt; //目前的水坑数
//八个方向
int dx[8] = {0, 0, -1, 1, -1, 1, -1, 1};
int dy[8] = {1, -1, 0, 0, -1, -1, 1, 1};
//广度优先搜索
void bfs(int x, int y) {
//队列
queue<coord> q;
q.push({x, y});
while (!q.empty()) {
//队列头
auto p = q.front();
q.pop();
//修改为.,防止再次更新
a[p.x][p.y] = '.';
//尝试八个方向
for (int k = 0; k < 8; k++) {
int x1 = p.x + dx[k], y1 = p.y + dy[k];//目标点坐标
if (x1 >= 1 && x1 <= n && y1 >= 1 && y1 <= m && a[x1][y1] == 'W')
q.push({x1, y1});
}
}
}
int main() {
//输入
cin >> n >> m;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
cin >> a[i][j];
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
//发现水坑
if (a[i][j] == 'W') {
//开始进行广度搜索
bfs(i, j);
//这个cnt++妙的很
cnt++;
}
cout << cnt << endl;
return 0;
}
2、深度优先算法
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
int n, m;
char a[N][N]; //地图
int cnt; //目前的水坑数
//八个方向
int dx[8] = {0, 0, -1, 1, -1, 1, -1, 1};
int dy[8] = {1, -1, 0, 0, -1, -1, 1, 1};
void dfs(int x, int y) {
//修改为.,防止再次更新
a[x][y] = '.';
//尝试八个方向
for (int k = 0; k < 8; k++) {
int x1 = x + dx[k], y1 = y + dy[k];//目标点坐标
if (x1 >= 1 && x1 <= n && y1 >= 1 && y1 <= m && a[x1][y1] == 'W')
dfs(x1, y1);
}
}
int main() {
//输入
cin >> n >> m;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
cin >> a[i][j];
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
//发现水坑
if (a[i][j] == 'W') {
dfs(i, j);
//这个cnt++妙的很
cnt++;
}
cout << cnt << endl;
return 0;
}