200. Number of Islands

The problem is to figure out how many blocks of data with the value "1" are in the matrix. The main idea is to traverse the matrix, when encountering an element of "1", perform a deep traversal of the element, and change the "1" element to a non-"1".

code show as below:

 

 1 class Solution {
 2     public int numIslands(char[][] grid) {
 3         int res = 0;
 4         if(grid == null || grid.length == 0){
 5             return res;
 6         }
 7         
 8         int m = grid.length, n = grid[0].length;
 9         
10         for( int i = 0 ; i < m ; i++ ){
11             for( int j = 0 ; j < n ; j++){
12                 if(grid[i][j] == '1'){
13                     res ++;
14                     occupyIsland(grid, i, j);
15                 }
16             }
17         }
18         
19         return res;
20     }
21     
22     private void occupyIsland(char[][] grid, int i, int j){
23         grid[i][j] = '2';
24         
25         int m = grid.length, n = grid[0].length;
26         if( i+1 < m && grid[i+1][j] == '1'){
27             occupyIsland(grid, i+1, j);
28         }
29         if( j+1 < n && grid[i][j+1] == '1'){
30             occupyIsland(grid, i, j+1);
31         }
32         if( i-1 >= 0 && grid[i-1][j] == '1'){
33             occupyIsland(grid, i-1, j);
34         }
35         if( j-1 >= 0 && grid[i][j-1] == '1'){
36             occupyIsland(grid, i, j-1);
37         }        
38     }
39 }

 

 

END

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325249480&siteId=291194637