source
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
DFS Solution
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
using namespace std;
char garden[102][102];
int n,m;
void dfs(int i,int j)
{
if(i<1||j<1||i>n||j>m) return ;
garden[i][j]='.';
for(int dx=i-1;dx<=i+1;dx++)
for(int dy=j-1;dy<=j+1;dy++)
{
if(garden[dx][dy]=='W')
{
dfs(dx,dy);
}
}
}
int main()
{
int sum=0;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
cin>>garden[i][j];
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
{
if(garden[i][j]=='W')
{
dfs(i,j);
sum++;
}
}
printf("%d",sum);
}
BFS Solution
#include<cstdio>
#include<queue>
using namespace std;
int main()
{
char maze[102][102];
int n,m,sum=0;
pair<int,int> p;
queue<pair<int,int> > myqueue;
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++)
scanf("%s",maze[i]);
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(maze[i][j]=='W')
{
maze[i][j]='.';
myqueue.push(pair<int,int> (i,j));
while(!myqueue.empty())
{
p=myqueue.front();
myqueue.pop();
for(int dx=p.first-1;dx<=p.first+1;dx++)
for(int dy=p.second-1;dy<=p.second+1;dy++)
{
if(dx>-1&&dy>-1&&dx<n&&dy<m&&(maze[dx][dy]=='W'))
{
maze[dx][dy]='.';
myqueue.push(pair<int,int> (dx,dy));
}
}
}
sum++;
}
}
}
printf("%d",sum);
}