'commit'
This commit is contained in:
57
TangDou/LuoGuBook/P1596_BFS.cpp
Normal file
57
TangDou/LuoGuBook/P1596_BFS.cpp
Normal file
@@ -0,0 +1,57 @@
|
||||
#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[] = {0, 0, -1, 1, -1, 1, -1, 1};
|
||||
int dy[] = {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;
|
||||
}
|
||||
Reference in New Issue
Block a user