There is a garden of N * m in size, which accumulates water after rain. The water in the eight connections is considered to be connected together, and the total number of water troughs in the garden is determined (the eight connections are relative to the W * Part ).
***
* W *
***
Analysis: Starting from any W, the adjacent part is replaced. After one DFS operation, all the WS connected to the initial W are replaced with '.', that is, the Wa disappears. So until the graph does not contain W, the total number of DFS operations is the answer. Eight statuses are transferred in eight directions. Each grid is called once as a DFS parameter, so the complexity is O (8 * n * m) = O (N * m ).
1 # include <iostream> 2 using namespace STD; 3 4 5 Int n, m; 6 char field [100] [100]; 7 8 9 // current position 10 void DFS (int x, int y) 11 {12 // Replace the current position. 13 field [x] [Y] = '. '; 14 15 // cyclically traverse 8 moving directions 16 for (INT dx =-1; DX <= 1; DX ++) 17 {18 for (int dy =-1; dy <= 1; dy ++) 19 {20 // move to (NX, NY) Location 21 int Nx = x + dx, NY = Y + dy; 22 // determines whether the garden is in the garden, and whether there is water 23 if (0 <= NX & NX <n & 0 <= ny & ny <M & field [NX] [NY] = 'W ') 24 DFS (NX, NY); 25} 26} 27 28 return; 29} 30 31 int main () 32 {33 while (CIN> N> m) 34 {35 int res = 0; 36 for (INT I = 0; I <n; I ++) 37 {38 for (Int J = 0; j <m; j ++) 39 {40 CIN> Field [I] [J]; 41} 42} 43 44 45 for (INT I = 0; I <n; I ++) 46 {47 for (Int J = 0; j <m; j ++) 48 {49 // dfs50 if (field [I] [J] = 'W') 51 {52 DFS (I, j) from where W exists ); 53 res ++; 54} 55} 56} 57 cout <res <Endl; 58} 59 60 return 0; 61}
POJ2386-Lake counting