poj 2386 Lake Counting

来源:互联网 发布:苹果cms模板怎么安装 编辑:程序博客网 时间:2024/05/02 02:49
                                                                                                                                 Lake Counting
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 14703 Accepted: 7452

Description

Due to recent rains, water has pooled in various places in Farmer John's field, which is represented by a rectangle of N x M (1 <= N <= 100; 1 <= M <= 100) squares. Each square contains either water ('W') or dry land ('.'). Farmer John would like to figure out how many ponds have formed in his field. A pond is a connected set of squares with water in them, where a square is considered adjacent to all eight of its neighbors.

Given a diagram of Farmer John's field, determine how many ponds he has.

Input

* 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.

Output

* Line 1: The number of ponds in Farmer John's field.

Sample Input

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

Sample Output

3
题意: 判断w相连的区域共有多少个……
题解:很早之前做的水题,今天又打了一遍……
 
代码:
#include<iostream>using namespace std;char a[1000][1000];bool vis[1000][1000];int dfs(int i,int j){    if (a[i][j]=='.')        return 0;    if (a[i][j]=='W'&&!vis[i][j])    {        vis[i][j]=1;        dfs(i+1,j);        dfs(i-1,j);        dfs(i,j+1);        dfs(i,j-1);        dfs(i+1,j+1);        dfs(i-1,j-1);        dfs(i-1,j+1);        dfs(i+1,j-1);        return 1;    }    return 0;}int main(){    int ans=0;    int n,m;    cin>>n>>m;    for (int i=0;i<n;i++)    {        for (int j=0;j<m;j++)        {            cin>>a[i][j];            vis[i][j]=0;        }    }    for (int i=0;i<n;i++)    {        for (int j=0;j<m;j++)        {            if (dfs(i,j)) ans++;        }    }    cout<<ans<<endl;    return 0;}

原创粉丝点击