本文已参与「新人创作礼」活动,一起开启掘金创作之路。
[C++]Lake Counting–POJ 2386
Lake Counting:
有一个大小为N*M的园子,雨后积起了水。八连通的积水被认为是连接在一起的。请求出园子里总共有多少水洼?(八连通指的是下图中相对W的*部分)
***
*W*
***
输入格式:
Line 1: Two space-separated integers: N and M
Lines 2…N+1: M characters per line representing one row of Farmer John’s field. Each character is either ‘W’ or ‘.’. The characters do not have spaces between them.
输出格式:
Line 1: The number of ponds in Farmer John’s field.
输入样例:
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
解题思路:搜寻W,从任意的W开始,通过dfs把与这个W连接的W用.代替,直到一次dfs结束。不断用dfs直到所有的w变成.,便可计算水洼个数
#include<iostream>
using namespace std;
const int maxn = 1000;
int n, m;
char lake[maxn][maxn];
int dfs(int x, int y){
lake[x][y] = '.';
for(int dx = -1; dx<=1; dx++){
for(int dy = -1; dy<=1; dy++){
int nx = x+dx;
int ny = y+dy;
if(0<=nx && nx < n && 0<=ny && ny < m && lake[nx][ny] == 'W') dfs(nx, ny);
}
}
return 1;
}
int main(){
cin>>n>>m;
for(int i = 0; i<n; i++){
for(int j = 0; j<m; j++){
cin>>lake[i][j];
}
}
int res = 0;
for(int i = 0; i<n; i++){
for(int j = 0; j<m; j++){
if(lake[i][j] == 'W'){
dfs(i, j);
res++;
}
}
}
cout<<res<<endl;
return 0;
}