传送门:牛客
题目描述:
Due to recent rains, water has pooled in various places in Farmer John's field, which is represented by a
rectangle of N x M (1 <= N <= 100; 1 <= M <= 100) squares. Each square contains either water ('W') or dry
land ('.'). Farmer John would like to figure out how many ponds have formed in his field. A pond is a
connected set of squares with water in them, where a square is considered adjacent to all eight of its
neighbors.
Given a diagram of Farmer John's field, determine how many ponds he has.
输入:
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
emmm,一道经典的求连通块的题目,在这道没有任何其他需求的题目中,DFS应该是一种比较简单的方法(当然BFS也是可以的),虽然我们的并查集
也是可以求连通块的(可以试着做一做,在本博客不做介绍)
主要思路:
- 首先我们直接开始枚举每一个水坑(如果合格水坑并没有加入到其他的联通块之中的话),我们将ans+1,然后将这个位置染色,并且由这个位置开始搜索,找出所有的与其联通的水坑,将其继续染色,这样我们就枚举了一个个的连通块
下面是具体的代码部分:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <string.h>
#include <stack>
#include <deque>
using namespace std;
typedef long long ll;
#define inf 0x3f3f3f3f
#define root 1,n,1
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
inline ll read() {
ll x=0,w=1;char ch=getchar();
for(;ch>'9'||ch<'0';ch=getchar()) if(ch=='-') w=-1;
for(;ch>='0'&&ch<='9';ch=getchar()) x=x*10+ch-'0';
return x*w;
}
#define maxn 1000000
#define ll_maxn 0x3f3f3f3f3f3f3f3f
const double eps=1e-8;
int n,m;
char mp[200][200];
int vis[200][200];
int dx[8]={1,1,1,0,-1,-1,-1,0};
int dy[8]={1,0,-1,-1,-1,0,1,1};;
void dfs(int x,int y) {
for(int i=0;i<=7;i++) {
int xx=x+dx[i],yy=y+dy[i];
if(xx<1||yy<1||xx>n||yy>m||vis[xx][yy]==1||mp[xx][yy]=='.') continue;
vis[xx][yy]=1;//进行一个染色操作
dfs(xx,yy);
}
return ;
}
int main() {
n=read();m=read();
for(int i=1;i<=n;i++) {
for(int j=1;j<=m;j++) {
cin>>mp[i][j];
}
}
int ans=0;
for(int i=1;i<=n;i++) {
for(int j=1;j<=m;j++) {
if(mp[i][j]=='W'&&vis[i][j]!=1) {
ans++;
dfs(i,j);
}
}
}
cout<<ans<<endl;
return 0;
}