Lake Counting
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 26533 | Accepted: 13329 |
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.
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.
* 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
基本的想法是每次找到一个池子后都让它“彻底消失”,也就是不会对以后的计数产生影响。由于池子采用的是八连通的定义方法,对于每次找到的'W'格都采用深度优先算法,让这个池子延伸到的每一个地方都被考虑到,然后“彻底消失”。
#include <cstdio>
#include <iostream>
using namespace std;
char pool[100][100];
int N,M;
int sum = 0;
void fill(int n, int m)
{
bool l=false,r=false,u=false,d=false;
if (pool[n][m] == 'W')
{
pool[n][m] = '.';
if (n > 0)
{
fill(n - 1, m);
l = true;
}
if (n < N)
{
fill(n + 1, m);
r = true;
}
if (m > 0)
{
fill(n, m - 1);
u = true;
}
if (m < M)
{
fill(n, m + 1);
d = true;
}
if (l&&u) //感觉这样用四个bool参数分类格子比较清楚
fill(n - 1, m - 1);
if (l&&d)
fill(n - 1, m + 1);
if (r&&u)
fill(n + 1, m - 1);
if (r&&d)
fill(n + 1, m + 1);
}
}
void dfs()
{
for (int n = 0; n < N; n++)
for (int m = 0; m < M; m++)
{
if (pool[n][m] == 'W')
{
fill(n, m);
sum++;
}
}
}
int main()
{
scanf("%d %d",&N,&M);
for (int n = 0; n < N; n++)
scanf("%s",pool[n]); //输入格式中'.'和'W'字符之间没有空格,就用%s来控制输入
dfs();
printf("%d",sum);
return 0;
}