Number of Puddles code (C)
This address: Http://blog.csdn.net/caroline_wendy
Title: There is a garden of n*m size, the rain has been stagnant. Eight connected water is felt to be connected together. Ask how many puddles there are in the garden together.
Using Depth-first search (DFS), in a puddle, look in 8 directions until all the connected water is found. Specify the next puddle again until there is no puddle .
The number of full depth-first searches is the number of puddles. time Complexity O (8*m*n) =o (m*n).
Code:
/* * main.cpp * * Created on:2014.7.12 * author:spike * * #include <stdio.h> #include <stdlib.h> #include <string.h># Include <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&&n x<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); r es++;}}} printf ("result =%d\n", res);}}; int main (void) {program P; P.solve (); return 0;}
Output:
result = 3
Programming algorithms-Number of puddles code (C)