Lake Counting
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 131072/65536K (Java/Other)
Problem 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< br>< br>* 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
Sample Output
3
题意: w就是水坑,边上八个位置 有w的话 就算他们是相连的
求总共有多少个水坑。 很直接的dfs算法。
#include <iostream>
#include <cstring>
using namespace std;
char map1[110][110];
int f[110][110];
void dfs(int x, int y)
{
if(f[x][y]==1||map1[x][y]=='.'||map1[x][y]==0)
return;
f[x][y] = 1;
dfs(x-1,y-1);
dfs(x-1,y);
dfs(x-1,y+1);
dfs(x,y-1);
dfs(x,y+1);
dfs(x+1,y-1);
dfs(x+1,y);
dfs(x+1,y+1);
}
int main()
{
memset(map1,0,sizeof(map1));
memset(f,0,sizeof(f));
int m,n,con = 0;
cin >> m >> n;
for(int i = 1; i<=m; ++i)
for(int j = 1; j<=n; ++j)
cin >> map1[i][j];
for(int i = 1; i <= m; ++i)
for(int j = 1; j <= n; ++j)
{
if(!f[i][j] && map1[i][j] == 'W')
{
con++;
dfs(i,j);
}
}
cout << con<<endl;
return 0;
}