Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 20003 | Accepted: 10063 |
Description
Given a diagram of Farmer John's field, determine how many ponds he has.
Input
* 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
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
Hint
There are three ponds: one in the upper left, one in the lower left,and one along the right side.
#include <string.h>
#include <stdlib.h>
char map[101][101];
int vt[101][101];
int dir[8][2] = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}};
int n, m;
void dfs(int x, int y)
{
int i;
for(i=0; i<8; i++)
{
int xx = x + dir[i][0];
int yy = y + dir[i][1];
if(map[xx][yy]=='W' && xx>=0 && xx<m && yy>=0 && yy<n && vt[xx][yy]==0 )
{
vt[xx][yy] = 1;
dfs(xx, yy);
}
}
}
int main()
{
int cnt;
int i, j;
while(scanf("%d %d%*c", &m, &n)!=EOF)
{
if(m==0 && n==0)
break;
cnt = 0;
memset(vt, 0, sizeof(vt));
for(i=0; i<m; i++)
{
scanf("%s", map[i]);
}
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
if(map[i][j]=='W' && vt[i][j]==0)
{
vt[i][j] = 1;
cnt++;
dfs(i, j);
}
}
}
printf("%d\n", cnt);
}
return 0;
}