首页 > 其他 > 详细

POJ 2386 Lake Counting

时间:2017-01-17 00:30:27      阅读:185      评论:0      收藏:0      [点我收藏+]

http://poj.org/problem?id=2386

思路 将联通的W变为 . dfs的次数 就是pound的个数

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <string.h>
 4 
 5 using namespace std;
 6 
 7 const int maxsize = 128;
 8 int M,N,cnt = 0;
 9 int d[2][8] = { {-1, -1, -1, 0, 1, 1, 1, 0},
10                 {-1, 0, 1, 1, 1, 0, -1, -1},
11               };
12 char court[maxsize][maxsize];
13 
14 //思路 : 随机选择一个水点 然后深搜将周围的所有水点变为.直到没有W为止
15 //那么深搜的次数 就是pound的个数
16 bool check(int x, int y)
17 {
18     if (x < 0 || x >= M || y < 0 || y >= N) return false;
19     if (court[x][y] == .) return false;
20     return true;
21 }
22 void dfs(int x, int y)
23 {
24     int nx, ny;
25     court[x][y] = .;//将相邻的所有W置为.
26     for (int i = 0; i <8; i++)
27     {
28         nx = x+d[0][i];
29         ny = y+d[1][i];
30         if (check(nx,ny))
31         {
32             dfs(nx, ny);
33         }
34     }
35 }
36 
37 int main()
38 {
39     //POJ是不能这样滴
40    #ifndef OLINE_JUDGE
41    freopen("in.txt", "r", stdin);
42    #endif // OLINE_JUDGE
43 
44    while (~scanf("%d%d", &M, &N))
45    {
46        cnt = 0;
47        getchar();
48        for (int i = 0;i < M; i++)
49        {
50            gets(court[i]);
51        }
52        while (1)
53        {
54            int x, y, s = 0;
55            for (int i = 0; i < M; i++)
56            {
57                for (int j = 0; j < N; j++)
58                {
59                    if (court[i][j] == W)
60                    {
61                        s++;
62                        x = i;
63                        y = j;
64                    }
65                }
66            }
67            if (s == 0) break;
68            dfs(x,y);
69            //for (int i = 0; i < M; i++) printf("%s\n",court[i]);
70            //putchar(‘\n‘);
71            cnt++;//进行多少次dfs()就有多少个pound
72        }
73        /*
74        改进:书上代码 自己想得太多
75        for (int i = 0; i < M; i++)
76         for (int j = 0; j < N; j++)
77        {
78          if (court[i][j] == ‘W‘)
79          {
80             dfs(i,j);
81             cnt++;
82          }
83        }
84 
85        */
86        printf("%d\n", cnt);
87    }
88    return 0;
89 
90 }
91 //时间复杂度 因为每个格子至多被访问一次 然后会想8个方向搜索 所以时间复杂度 O(8*M*N)

 

POJ 2386 Lake Counting

原文:http://www.cnblogs.com/oscar-cnblogs/p/6291447.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!