刷题记录:牛客NC24739Lake Counting

这是一篇关于如何使用深度优先搜索(DFS)解决二维矩阵中连通水坑数量的问题。题目要求在给定的农田矩形网格中,找出所有相互连通的水坑形成多少个独立的池塘。DFS是一种有效的解决方法,通过遍历每个水坑并染色来避免重复计数。代码示例中展示了如何实现这一算法,遍历每个位置,遇到未染色的水坑时递增答案并进行DFS搜索。
摘要由CSDN通过智能技术生成

传送门:牛客

题目描述:

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也是可以的),虽然我们的并查集也是可以求连通块的(可以试着做一做,在本博客不做介绍)

主要思路:

  1. 首先我们直接开始枚举每一个水坑(如果合格水坑并没有加入到其他的联通块之中的话),我们将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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值