poj2386 Lake Counting

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

有一个N*M的矩形,'W'表示积水,'.'表示干的陆地,积水在其相邻的8个方向上如果有其它积水,那么认为这些积水是连通的,现在需要判断这块矩形中有多少块这样完全连同的积水。

输入样例

10 12
W........WW.
.WWW.....WWW
....WW...WW.
.........WW.
.........W..
..W......W..
.W.W.....WW.
W.W.W.....W.
.W.W......W.
..W.......W.

输出样例:

3

思路

  • 使用dfs判断联通块的数目,注意需要将访问过的格点做标记(这里直接将'W'的格子替换为'.'即可)。

  • 使用getchar()接收输入,注意输入是否正确接收。

代码

#include <iostream>
using namespace std;
const int N = 100;
int n, m;
char field[N][N];
const int raw[] = {0, 0, 1, -1, 1, 1, -1, -1};
const int col[] = {1, -1, 0, 0, 1, -1, -1, 1};

void dfs(int i, int j){
    field[i][j] = '.';
    for(int k = 0; k < 8; ++k){
        if(i+col[k]>=0 && i+col[k]<n && j+raw[k]>=0 && j+raw[k]<m && field[i+col[k]][j+raw[k]] == 'W'){
            dfs(i+col[k], j+raw[k]);
        }
    }
}

int main(){
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
    scanf("%d%d", &n, &m);
    for(int i = 0; i < n; ++i)
        for(int j = 0; j < m; ++j){
            char c; while((c = getchar()) == '\n'); // 跳过空格
            field[i][j] = c;
        }
    
   int cnt = 0;
   for(int i = 0; i < n; ++i){
       for(int j = 0; j < m; ++j){
           if(field[i][j] == 'W'){
               dfs(i, j);
               ++cnt;
           }
       }
   }
    printf("%d", cnt);    
}

猜你喜欢

转载自www.cnblogs.com/patrolli/p/12188641.html