首页 > 代码库 > UVa 10946 - You want what filled?

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;
}

UVa 10946 - You want what filled?