POJ 2386 Lake Counting

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)
复制代码

 

posted @   Lorazepam  阅读(263)  评论(0编辑  收藏  举报
编辑推荐:
· 后端思维之高并发处理方案
· 理解Rust引用及其生命周期标识(下)
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
阅读排行:
· 后端思维之高并发处理方案
· 千万级大表的优化技巧
· 在 VS Code 中,一键安装 MCP Server!
· 10年+ .NET Coder 心语 ── 继承的思维:从思维模式到架构设计的深度解析
· 上周热点回顾(3.24-3.30)
点击右上角即可分享
微信分享提示