深搜,找到所有的‘#’连通域

找到所有的‘#’连通域

输入
5 6
x#xxxx
xx#xxx
xx#xx#
xxx##x
x#xxxx

输出
5

#include <iostream>
#include <cstring>
using namespace std;
char maze[110][110];
bool vis[110][110];
int n,m;
int cnt=0;
void dfs (int x,int y)
{
	if (x<0||x>=n||y<0||y>=m){
		return ;
	}
	if (maze[x][y]=='#'&&!vis[x][y])
	{
		vis[x][y]=true;
	} else {
		return ;
	}
	dfs (x+1,y);
	dfs (x,y+1);
	dfs (x-1,y);
	dfs (x,y-1);
	return ;
}
int main ()
{
	cin>>n>>m;
	for (int i=0;i<n;i++){
		cin>>maze[i];
	} 
	for (int i=0;i<n;i++){
		for (int j=0;j<m;j++){
			if (maze[i][j]=='#'&&!vis[i][j]){
				cnt++;
				dfs (i,j);
			}
		} 
	}
	cout<<cnt<<endl;
	return 0;
}

详解欢迎关注我的公众号:王同学的蓝桥杯训练营

### 计算最大连通域数量 为了计算二维数组中由字符&#39;X&#39;(表示陆地)构成的最大连通域的数量,可以采用度优先索 (DFS) 或广度优先索 (BFS) 来遍历整个地图。每当遇到一个新的未访问过的‘X’时,启动一次新的索过程来标记这个连通区域内的所有位置。 #### 方法概述 通过迭代每一个网格单元格,当发现一个尚未处理的`&#39;X&#39;`时,即认为找到了一片新大陆,并增加岛屿计数器;随后利用递归方式探索相邻四个方向上的其他`&#39;X&#39;`直到无法继续为止,在此期间将所经过的地方做上记号防止重复统计[^1]。 ```python def max_area_of_island(grid): if not grid or not grid[0]: return 0 rows, cols = len(grid), len(grid[0]) def dfs(r, c): # Check boundary conditions and whether the cell is land (&#39;X&#39;) if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != &#39;X&#39;: return 0 area = 1 grid[r][c] = &#39;#&#39; # Mark as visited # Explore all four possible directions from this point. for dr, dc in ((-1, 0), (+1, 0), (0, -1), (0, +1)): nr, nc = r + dr, c + dc area += dfs(nr, nc) return area largest_area = 0 for row in range(rows): for col in range(cols): if grid[row][col] == &#39;X&#39;: current_area = dfs(row, col) largest_area = max(largest_area, current_area) return largest_area ``` 上述代码实现了寻找并返回最大的连通域面积的功能。对于每个起点为`&#39;X&#39;`的位置调用`dfs()`函数执行操作,同时记录下当前正在考察的是哪一块连续的土地,并且更新全局变量`largest_area`保存目前为止见过的最大值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值