uva 657 - The die is cast

需要两层dfs,第一层找骰子,第二层在骰子里找点数。递归时访问过的节点记得标记用以结束递归。

 

 

#include<stdio.h>
#include<stdlib.h>

char map[55][55];
int w, h;
int count;

int num;
int arr[1000];
int idx = 1;

void subDfs(int i, int j) {
	if (i < 0 || j < 0 || i >= h || j >= w)
		return;
	if (map[i][j] == '*' || map[i][j] == '.' || map[i][j] == '0'
			|| map[i][j] == '1')
		return;

	map[i][j] = '1';

	subDfs(i - 1, j);
	subDfs(i + 1, j);
	subDfs(i, j - 1);
	subDfs(i, j + 1);

}

void dfs(int i, int j) {
	if (i < 0 || j < 0 || i >= h || j >= w)
		return;
	if (map[i][j] == '.' || map[i][j] == '0')
		return;

	if (map[i][j] == 'X') {
		subDfs(i, j);
		num++;
	}

	map[i][j] = '0';

	dfs(i - 1, j);
	dfs(i + 1, j);
	dfs(i, j - 1);
	dfs(i, j + 1);

}

int cmp(const void*a, const void*b) {
	return *(int*) a - *(int*) b;
}

int main() {
	setbuf(stdout,NULL);
	while (scanf("%d%d", &w, &h) != EOF) {
		if (w == 0)
		break;
		getchar();
		int i, j;
		for (i = 0; i < h; i++) {
			for (j = 0; j < w; j++) {
				scanf("%c", &map[i][j]);
			}
			getchar();
		}

		count = 0;
		for (i = 0; i < h; i++) {
			for (j = 0; j < w; j++) {
				if (map[i][j] == '*') {
					num = 0;
					dfs(i,j);
					arr[count++] = num;
				}
			}
		}

		qsort(arr, count, sizeof(arr[0]), cmp);

		printf("Throw %d\n", idx++);
		for (i = 0; i < count; i++) {
			printf("%d", arr[i]);
			if (i != count - 1)
			printf(" ");
		}
		printf("\n\n");

	}

	return 0;
}

 

你可能感兴趣的:(uva 657 - The die is cast)