Number of puddles algorithm code (C)

Source: Internet
Author: User

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

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.