UVa 657 - The die is cast

  题目大意:给一副数字化的图像,上面有若干个色子,每个色子有若干个连通分量代表点数,让你求出每个色子的点数。

  开始没什么思路,只是知道要用dfs,可是如何深搜很是纠结,只好研究别人代码...首先进行一次搜索,对每一个色子进行染色(进行不同的标记),然后再进行一次搜索,寻找点(标记为X)的连通分量,之后根据它的颜色判断是哪一个色子的,相应的色子的点数加一。最后可以得出每个色子的点数,果然,换一个角度,世界大不同啊

 1 #include <cstdio>
 2 #include <algorithm>
 3 #include <cstring>
 4 using namespace std;
 5 #define MAXN 60
 6 
 7 char pic[MAXN][MAXN];
 8 int vis[MAXN][MAXN], color[MAXN][MAXN];
 9 int ans[3000];
10 int n, m;
11 
12 void dice_dye(int x, int y, int c)
13 {
14     if (x < 0 || x >= n || y < 0 || y >= m || color[x][y] || pic[x][y] == '.')  return;
15     color[x][y] = c;
16     dice_dye(x-1, y, c);
17     dice_dye(x, y-1, c);
18     dice_dye(x, y+1, c);
19     dice_dye(x+1, y, c);
20 }
21 
22 void dfs(int x, int y)
23 {
24     if (x < 0 || x >= n || y < 0 || y >= m || vis[x][y] || pic[x][y] != 'X')  return;
25     vis[x][y] = 1;
26     dfs(x-1, y);
27     dfs(x, y-1);
28     dfs(x, y+1);
29     dfs(x+1, y);
30 }
31 
32 int main()
33 {
34 #ifdef LOCAL
35     freopen("in", "r", stdin);
36 #endif
37     int kase = 0;
38     while (scanf("%d%d", &m, &n) && (n || m))
39     {
40         for (int i = 0; i < n; i++)
41             scanf("%s", pic[i]);
42         memset(color, 0, sizeof(color));
43         int dice_num = 0;
44         for (int i = 0; i < n; i++)
45             for (int j = 0; j < m; j++)
46                 if (pic[i][j] != '.' && !color[i][j])
47                 {
48                     ++dice_num;
49                     dice_dye(i, j, dice_num);
50                 }
51         memset(ans, 0, sizeof(ans));
52         memset(vis, 0, sizeof(vis));
53         for (int i = 0; i < n; i++)
54             for (int j = 0; j < m; j++)
55                 if (pic[i][j] == 'X' && !vis[i][j])
56                 {
57                     dfs(i, j);
58                     ans[color[i][j]-1]++;
59                 }
60         sort(ans, ans+dice_num);
61         printf("Throw %d\n", ++kase);
62         for (int i = 0; i < dice_num; i++)
63             printf("%d%s", ans[i], (i == dice_num-1) ? "\n" : " ");
64         printf("\n");
65     }
66     return 0;
67 }
View Code

 

posted @ 2013-09-12 17:49  xiaobaibuhei  阅读(235)  评论(0编辑  收藏  举报