POJ2386-Lake counting

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.