题目描述:
有一个大小为N*M的园子,雨后积水。八连通的积水被认为是一个水洼,求园子共有多少水洼。
八连通示意图(相对W的连通部分用*标记)
* * *
* W *
* * *
限制条件
N,M<=100
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
思路:显然的dfs,每次dfs到W做标记即可。
#include<iostream>
#include<cstdio>
using namespace std;
char fied[105][105];
int N,M;
int main()
{
void dfs(int x,int y);
int cnt=0;
cin>>N>>M;
for(int x=0;x<N;x++)
for(int y=0;y<M;y++)
{
do ;
while((fied[x][y]=getchar())=='\n');
}
for(int x=0;x<N;x++)
for(int y=0;y<M;y++)
if(fied[x][y]=='W')
{
// printf("*");
dfs(x,y);
cnt++;
}
cout<<cnt<<endl;
return 0;
}
void dfs(int x,int y)
{
fied[x][y]='.'; // 标记
for(int dx=-1;dx<=1;dx++)
for(int dy=-1;dy<=1;dy++)
{
int nx=x+dx,ny=y+dy;
if(0<=nx&&nx<N&&0<=ny&&ny<M&&fied[nx][ny]=='W') dfs(nx,ny);
}
}