200. Number of Islands

Posted sysu_kww

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了200. Number of Islands相关的知识,希望对你有一定的参考价值。

该题目要算出矩阵中有多少个数值为“1”的数据块。主要思路是对矩阵进行遍历,遇到“1”的元素的时候,对元素进行深度遍历,并将“1”元素改为非“1”。

代码如下:

 

 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

以上是关于200. Number of Islands的主要内容,如果未能解决你的问题,请参考以下文章

200. Number of Islands

200. Number of Islands

200. Number of Islands

200. Number of Islands

200. Number of Islands

200. Number of Islands