poj2386

来源:互联网 发布:软件新品发布会 ppt 编辑:程序博客网 时间:2024/04/30 06:32

Lake Counting
Time Limit: 1000MS Memory Limit: 65536K

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 12
**W……..WW.
.WWW…..WWW
….WW…WW.
………WW.
………W..
..W……W..
.W.W…..WW.
W.W.W…..W.
.W.W……W.
..W…….W.**

Sample Output

3

There are three ponds: one in the upper left, one in the lower left,and one along the right side.

思路: 类似石油田数。 简单深搜:
如有不足或你有更好的思路,还请提出。

AC代码:

#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#include <queue>#include <stack>#include <set>#define INF 0x3f3f3f#define ll long longusing namespace std;int dir[8][2]={{1,0},{-1,0},{1,1},{1,-1},{0,1},{0,-1},{-1,1},{-1,-1}};char Map[101][101];int n,m;int sum;void dfs(int x,int y){    int tx,ty;    for(int i=0; i<8; i++){        tx=x+dir[i][0];        ty=y+dir[i][1];        if(tx>=1&&tx<=n&&ty>=1&&ty<=m&&Map[tx][ty]=='W'){            Map[tx][ty]='.';            dfs(tx,ty);        }    }}int main(){    while(scanf("%d%d",&n,&m)!=EOF&&n&&m){        sum=0;        for(int i=1;i<=n; i++){            for(int j=1; j<=m; j++){                cin>>Map[i][j];            }        }        for(int i=1;i<=n;i++){            for(int j=1;j<=m;j++){                if(Map[i][j]=='W'){                    Map[i][j]='.';                    dfs(i,j); sum++;                }            }        }        printf("%d\n",sum);    }    return 0;}
0 0
原创粉丝点击