Lake Counting--POJ 2386

[C++]Lake Counting–POJ 2386

Lake Counting:
有一個大小爲N*M的園子,雨後積起了水。八連通的積水被認爲是連接在一起的。請求出園子裏總共有多少水窪?(八連通指的是下圖中相對W的*部分)
***
*W*
***
輸入格式:
Line 1: Two space-separated integers: N and M
Lines 2…N+1: M characters per line representing one row of Farmer John’s field. Each character is either ‘W’ or ‘.’. The characters do not have spaces between them.
輸出格式:
Line 1: The number of ponds in Farmer John’s field.
輸入樣例:
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

解題思路:搜尋W,從任意的W開始,通過dfs把與這個W連接的W用.代替,直到一次dfs結束。不斷用dfs直到所有的w變成.,便可計算水窪個數

#include<iostream>
using namespace std;

const int maxn = 1000;

int n, m;
char lake[maxn][maxn];

int dfs(int x, int y){
    lake[x][y] = '.';
    
    for(int dx = -1; dx<=1; dx++){
        for(int dy = -1; dy<=1; dy++){
            int nx = x+dx;
            int ny = y+dy;
            if(0<=nx && nx < n && 0<=ny && ny < m && lake[nx][ny] == 'W') dfs(nx, ny);
        }
    }
    
    return 1;   
}

int main(){
    cin>>n>>m;
    
    for(int i = 0; i<n; i++){
        for(int j = 0; j<m; j++){
            cin>>lake[i][j];
        }
    }
    
    int res = 0;
    for(int i = 0; i<n; i++){
        for(int j = 0; j<m; j++){
            if(lake[i][j] == 'W'){
                dfs(i, j);
                res++;
            }
        }
    }
    
    cout<<res<<endl;
    
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章