LC 200 Number of Islands

Problem Description

Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

Input:
11110
11010
11000
00000

Output: 1

Example 2:

Input:
11000
11000
00100
00011

Output: 3

Answers

. 1  class Solution {
 2  public :
 . 3      void foo (Vector <Vector < char >> & Grid, int I, int J) {
 . 4          IF (I < 0 || J < 0 || I> = grid.size () || J> = Grid [ 0 ] .size ()) return ;
 . 5          IF (Grid [I] [J] == ' 0 ' ) return ; // to prepare recursive stop condition 
. 6          Grid [I] [J] = ' 0 ' ; // to avoid repetition, the detected value of zero through 
7         foo(grid,i-1,j);
 8         foo(grid,i+1,j);
 9         foo(grid,i,j-1);
10         foo(grid,i,j+1);
11         
12     }
13    
14     int numIslands(vector<vector<char>>& grid) {
15         int counter = 0;
16         for(int i = 0; i<grid.size();i++){
17             for(int j = 0; j<grid[i].size();j++){
18                 if(grid[i][j] == '1'){
19                     counter ++;
20                     foo(grid,i,j);
21                 }
22             }
23         }
24         return counter;
25     }
26 };

 

Supplementation

VL

This question reminds me of the seeded region growing algorithm (Seeded Regin Growing Mathimatics-Numerical algorithms) , with reference to what other people's answers, really very similar.

The basic idea is: a planted seed (first region encountered), then let it grow (recursively). If the same region, on growth (lines 7-10), if different (lines 4-5), is stopped.

Because the region is grown from seed in order, to all neighboring regions tag label, to better identify the image. But there is no need label, just need to counter.

Prevent duplicate

From the initial point, it begins to grow, because the same recursive rules, it will enter a recursive initial point, in order to prevent repetition, as long as the contact region, the entire re-assignment is 0. (6 lines)

It is indeed a very clever approach.

 

Guess you like

Origin www.cnblogs.com/kykai/p/11421700.html