传送门UVa 657 - The die is cast
题意是统计输入数据中, 每个骰子中的独立的X的个数.
关键:
1. 如何知道区分每个骰子?
对骰子进行DFS.
2.如何得到X的数目?
在骰子中对X进行DFS
因此, 这是一个DFS中包含DFS的题目.
就像求导, 先对骰子整体"求导", 再对X "求导".
详情见代码
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; int ans[10000]; char in[60][60]; int num; void DFSPoint(int x, int y); void DFSDice(int x, int y); int main() { //freopen("input.txt", "r", stdin); int i, j,cases = 1, cnt; int row, col; while (scanf("%d%d", &col, &row)) { getchar(); cnt = 0; memset(in, 0, sizeof(in)); memset(ans, 0, sizeof(ans)); if (row + col == 0) break; for (i = 1; i <= row; i++) scanf("%s", in[i] + 1); for (i = 1; i <= row; i++) { for (j = 1; j <= col; j++) { if (in[i][j] == '*' || in[i][j] == 'X') { num = 0; DFSDice(i, j); ans[cnt++] = num; } } } sort(ans, ans + cnt); printf("Throw %d\n%d", cases++, ans[0]); for (i = 1; i < cnt; i++) printf(" %d", ans[i]); printf("\n\n"); } return 0; } void DFSPoint(int x, int y) { if (in[x][y] != 'X') return; in[x][y] = '*'; DFSPoint(x - 1, y); DFSPoint(x, y + 1); DFSPoint(x + 1, y); DFSPoint(x, y - 1); } void DFSDice(int x, int y) { if (in[x][y] != '*' && in[x][y] != 'X') return; if (in[x][y] == 'X') { num++; DFSPoint(x, y); } in[x][y] = '.'; DFSDice(x - 1, y); DFSDice(x, y + 1); DFSDice(x + 1, y); DFSDice(x, y - 1); }