• 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
    ",court[i]);
    70            //putchar('
    ');
    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
    ", cnt);
    87    }
    88    return 0;
    89 
    90 }
    91 //时间复杂度 因为每个格子至多被访问一次 然后会想8个方向搜索 所以时间复杂度 O(8*M*N)
  • 相关阅读:
    Xcode 6 下添加pch头文件
    兵器簿之github的配置和使用
    sql 2005性能调优
    C#遍历枚举(Enum)值
    使用 jQuery 调用 ASP.NET AJAX Page Method
    强制不使用“兼容性视图”的HTML代码
    HR在ERP实施过程中的作用
    WdatePicker日历添加事件,在任意月改变时处理日期事件
    JQuery实现表格自动增加行,对新行添加事件
    获取元素离文档各边的距离
  • 原文地址:https://www.cnblogs.com/oscar-cnblogs/p/6291447.html
Copyright © 2020-2023  润新知