Title: There is a garden of n*m size, the rain has accumulated water. The eight-connected stagnant water is considered to be connected together. Ask how many puddles there are in the garden altogether.
Use depth First search (DFS), and in a puddle, look in 8 directions until all the connected water is found. Specify the next puddle again until there is no puddle.
Then all the depth-first searches are the number of puddles. Time complexity O (8*m*n) =o (m*n).
Code:
* * * * * main.cpp * * * Created on:2014.7.12 * This column more wonderful content: HTTP://WWW.BIANCENG.CNHTTP://WWW.BIANCENG.CN/PROGRAMMING/SJJG /* author:spike * * #include <stdio.h> #include <stdlib.h> #include <string.h> #in
Clude <math.h> class Program {static const int max_n=20, MAX_M=20;
int N = ten, M = 12; Char field[max_n][max_m+1] = {"W ..... WW. ",". Www..... WWW "," .... Ww... WW. "," ..... WW. "," ..... W.. ",". W...... W.. ",". W.w ..... WW. "," W.W.W ... W. ",". W.W ... W. ",". W.......
W. "};
void Dfs (int x, int y) {field[x][y] = '. '; for (int dx =-1; DX <= 1; dx++) {for (int dy =-1; dy <= 1; dy++) {int NX = X+DX,
NY = Y+dy; if (0<=dx&&nx<n&&0<=ny&&ny<=m&&field[nx][ny]== ' W ') DFS (NX, NY);
} return;
} public:void Solve () {int res=0;
for (int i=0; i<n; i++) {for (int j=0; j<m; J + +) {if (field[i][j] = = ' W ') {
DFS (I,J);
res++;
} printf ("result =%d\n", res);
}
};
int main (void) {program P;
P.solve ();
return 0; }
Output:
result = 3
Author: csdn Blog Mystra