Shuidao's quantity code (c)
Address: http://blog.csdn.net/caroline_wendy
Question: There is a garden of N * m in size, and water accumulates after the rain. The water in the eight connections is considered to be connected together. How many sinks are there in the garden.
UseDeep Priority Search (DFS)FromEight directionsSearch until it is foundAll connected Stagnant Water. AgainSpecify the next wa,Until there are no sinksUntil.
Then allTimes of deep Priority SearchThat is, the number of sinks.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 = 10, 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