Description Due to recent rains, water have pooled in various places in Farmer John ' s field, which was represented by a rect Angle of N x m (1 <= n <=; 1 <= M <=) squares. Each square contains the either water (' W ') or dry land ('. '). Farmer John would like to figure out how many ponds has formed in his field. A pond is a connected set of squares with water in them, where a square was considered adjacent to all eight of its NEIGHBO Rs.
Given a diagram of Farmer John ' s field, determine how many ponds he had.
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 does not have spaces between them.
Output * Line 1:the number of ponds in Farmer John ' s field.
Sample Input
Ten Watts .....
WW.
. WWW.....WWW ...
. Ww... WW.
......... WW.
......... W ...
. W...... W ...
W.w ..... WW.
W.w.w ..... W.
. W.W ... W ...
W....... W.
Sample Output
3
Problem Solving Ideas:
The main idea is to ask you a few lakes in the figure, W in the eight directions around W. are classified as a lake, connected. DFS water problem, even backtracking is not required, directly in eight directions to search down, as long as the W, the ' W ' into '. '。 The goal is to not visit the previous W at the next retrieval time.
AC Code:
#include <iostream>
#include <cstdio>
using namespace std;
const int MAXN = + 5;
Char MAP[MAXN][MAXN];
int dir[8][2] = {{ -1,-1},{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1}}; Store eight directions in a two-dimensional array
int dfs (int x,int y,int n,int m)
{
int a, b;
Map[x][y] = '. '; The "W" that was visited was converted to "."
for (int i = 0;i < 8; i++)
{
a = x + dir[i][0];
B = y + dir[i][1];
if (a < n && a >= 0 && b < m && B >= 0 && map[a][b] = = ' W ')
Dfs (a, B, N, m );
}
return 1;
}
int main ()
{
int n, m, ans = 0;
scanf ("%d%d", &n, &m);
for (int i = 0; i < n; i++)
scanf ("%s", Map[i]);
for (int i = 0, i < n; i++) for
(int j = 0; J < m; j + +)
if (map[i][j]== ' W ') //Retrieve entire graph
ans + = DFS (i,j , n,m);
printf ("%d\n", ans);
return 0;
}