C++ quantitative algorithm for puddles of data structures

  • 2020-05-26 09:43:58
  • OfStack

C++ quantitative algorithm for puddles of data structures

Title: there is a garden of size N*M, and water has accumulated after the rain. 8 connected water is considered to be connected to 1. Ask how many puddles there are in the garden.

Using the depth-first search (DFS), search a puddle from 8 directions until all connected water is found. Specify the next puddle again until there is no puddle.
Time complexity O(8*M*N)=O(M*N).

Code:


/* 
 * main.cpp 
 * 
 * Created on: 2014.7.12 
 * More wonderful content in this column: http://www.bianceng.cn/Programming/sjjg/
 *   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

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: