ACM--dfs与bfs

本文介绍了一种使用深度优先搜索(DFS)算法来解决二维网格中寻找最大连通块的问题。连通块由相邻的填充单元格组成,包括水平、垂直和对角线方向的邻居。算法的目标是在给定的网格上找到最大的连通块,即包含最多填充单元格的区域。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.dfs求最大连通块(UVa 871 - Counting Cells in a Blob)

Consider a two-dimensional grid of cells, each of which may be empty
or filled. Filled cells form blobs. The filled cells that are connected
form the same bigger blob. Two cells are said to be connected if
they are adjacent to each other horizontally, vertically, or diagonally.
There may be several blobs on the grid. Your job is to find the largest
blob (in terms of number of cells) on the grid.
Write a program that determines the size of the largest blob for
a given set of blobs.
Input
The input begins with a single positive integer on a line by itself
indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also
a blank line between two consecutive inputs.
The grid is given as a set of strings, each composed of 0’s and 1’s. The ‘1’ indicates that the cell is
filled and ‘0’ indicates an empty cell. The strings should be converted into the grid format.
The largest grid that sould be considered is a 25×25 grid.
Output
For each test case, the output must follow the description below. The outputs of two consecutive cases
will be separated by a blank line.
The output is the size of the largest blob found on the grid.
Sample Input
1
11000
01100
00101
10001
01011
Sample Output
5
#include <iostream>
#include <cstdlib>
#include <cstdio>
 
using namespace std;
 
char maps[30][30],buf[30];
 
int dxy[8][2] = {1,-1,1,0,1,1,0,-1,0,1,-1,-1,-1,0,-1,1};
int dfs(int x, int y)
{
	if (x < 0 || y < 0) return 0;
	if (maps[x][y] != '1') return 0;
	maps[x][y] = '0';
	int sum = 1;
	for (int k = 0 ; k < 8 ; ++ k)
		sum += dfs(x+dxy[k][0], y+dxy[k][1]);
	return sum;
}
 
int main()
{
	int n;
	scanf("%d",&n);
	gets(buf);
	gets(buf);
	while (n --) {
		int count = 0;
		while (gets(maps[count]))
			if(!maps[count ++][0]) break;
		
		int Max = 0;
		for (int i = 0 ; i < count ; ++ i)
		for (int j = 0 ; maps[i][j] ; ++ j)
			if (maps[i][j] == '1')
				Max = max(Max, dfs(i, j));
		
		printf("%d\n",Max);
		if (n) printf("\n");
	}
	
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值