UVa 10946 - You want what filled?

题目:统计一个矩阵中所有的连通块的个数,按递减输出。

分析:搜索,floodfill。直接利用dfs求解即可。

说明:数组开小了╮(╯▽╰)╭。

#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>

using namespace std;

char maps[55][55];

typedef struct tnode
{
	char ch;
	int  count;
}type;
type data[2000];

int dfs(int x, int y, int n, int m, char c)
{
	if (x < 0 || x >= n || y < 0 || y >= m) 
		return 0;
	if (maps[x][y] != c) return 0;
	maps[x][y] = '.';
	int sum = 1;
	sum += dfs(x+1, y, n, m, c);
	sum += dfs(x-1, y, n, m, c);
	sum += dfs(x, y+1, n, m, c);
	sum += dfs(x, y-1, n, m, c);
	return sum;
}

int cmp(type a, type b)
{
	if (a.count != b.count)
		return a.count > b.count;
	return a.ch < b.ch;
}

int main()
{
	int n,m,temp,cas = 1;
	while (~scanf("%d%d",&n,&m) && m) {
		for (int i = 0 ; i < n ; ++ i)
			scanf("%s",maps[i]);
		
		int count = 0;
		for (int i = 0 ; i < n ; ++ i)
		for (int j = 0 ; j < m ; ++ j) 
			if (maps[i][j] != '.') {
				data[count].ch = maps[i][j];
				data[count].count = dfs(i, j, n, m, maps[i][j]);
				count ++;
			}
		
		sort(data, data+count, cmp);
		
		printf("Problem %d:\n",cas ++);
		for (int i = 0 ; i < count ; ++ i)
			printf("%c %d\n",data[i].ch,data[i].count);
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值