东方博宜OJ 1435:数池塘(八方向)← Flood fill
● 本题代码与“AcWing 1097:池塘计数:https://blog.csdn.net/hnjzsyjyj/article/details/118642238”的代码一模一样。
【题目来源】
https://oj.czos.cn/p/1435
https://www.acwing.com/problem/content/1099/
【题目描述】
农夫约翰的农场可以表示成 N×M(1≤N, M≤100)个方格组成的矩形。由于近日的降雨,在约翰农场上的不同地方形成了池塘。
每一个方格或者有积水("W')或者没有积水(.)。农夫约翰打算数出他的农场上共形成了多少池塘。一个池塘是一系列相连的有积水的方格,每一个方格周围的八个方格都被认为是与这个方格相连的。
现给出约翰农场的图样,要求输出农场上的池塘数。
【输入格式】
第 1 行:由空格隔开的两个整数:N 和 M;
第 2~N+1行:每行 M 个字符代表约翰农场的一排方格的状态。每个字符或者是 'W' 或者是 '.',字符之间没有空格。
【输出格式】
输出只有 1 行,输出约翰农场上的池塘数。
【输入样例】
10 12
W........WW.
.WWW.....WWW
....WW...WW.
.........WW.
.........W..
..W......W..
.W.W.....WW.
W.W.W.....W.
.W.W......W.
..W.......W.
【输出样例】
3
【数据范围】
1≤N, M≤100
【算法分析】
● 本题代码与“AcWing 1097:池塘计数:https://blog.csdn.net/hnjzsyjyj/article/details/118642238”的代码一模一样。
【算法代码一:dfs】
#include <bits/stdc++.h>
using namespace std;
const int N=1e3+5;
char mp[N][N];
int dx[]= {1,1,0,-1,-1,-1,0,1};
int dy[]= {0,1,1,1,0,-1,-1,-1};
int n,m,ans;
void dfs(int x,int y) {
/*Mark the current position as '.'
to indicate that it has been visited,
in order to avoid redundant processing.*/
mp[x][y]='.';
for(int i=0; i<8; i++) {
int tx=x+dx[i];
int ty=y+dy[i];
if(mp[tx][ty]=='W') {
dfs(tx,ty);
}
}
}
int main() {
cin>>n>>m;
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
cin>>mp[i][j];
}
}
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
if(mp[i][j]=='W') {
dfs(i,j);
ans++;
}
}
}
cout<<ans<<endl;
return 0;
}
/*
in:
10 12
W........WW.
.WWW.....WWW
....WW...WW.
.........WW.
.........W..
..W......W..
.W.W.....WW.
W.W.W.....W.
.W.W......W.
..W.......W.
out:
3
*/
【算法代码二:bfs】
#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> PII;
const int N=1e3+5;
char mp[N][N];
int dx[]= {1,1,0,-1,-1,-1,0,1};
int dy[]= {0,1,1,1,0,-1,-1,-1};
int n,m,ans;
void bfs(int x,int y) {
queue<PII> q;
q.push({x,y});
mp[x][y]='.';
while(!q.empty()) {
PII t=q.front();
q.pop();
for(int i=0; i<8; i++) {
int tx=t.first+dx[i];
int ty=t.second+dy[i];
if(tx>=0 && ty>=0 && tx<n && ty<m && mp[tx][ty]=='W') {
mp[tx][ty]='.';
q.push({tx,ty});
}
}
}
}
int main() {
cin>>n>>m;
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
cin>>mp[i][j];
}
}
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
if(mp[i][j]=='W') {
bfs(i,j);
ans++;
}
}
}
cout<<ans<<endl;
return 0;
}
/*
in:
10 12
W........WW.
.WWW.....WWW
....WW...WW.
.........WW.
.........W..
..W......W..
.W.W.....WW.
W.W.W.....W.
.W.W......W.
..W.......W.
out:
3
*/
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/118642238
https://blog.csdn.net/hnjzsyjyj/article/details/158618461
更多推荐

所有评论(0)