n刷200.Number of islands

Medium
不知道做过多少回了,有时还是会出一些小bug.

详细讲解:https://www.youtube.com/watch?v=XSmgFKe-XYU


public class Solution {
    public int numIslands(char[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0){
            return 0;
        }
        int count = 0;
        int m = grid.length;
        int n = grid[0].length;
        for (int i = 0; i < m; i++){
            for (int j = 0; j < n; j++){
                if (grid[i][j] == '1'){
                    dfsSearch(i, j, grid);
                    count++;
                }
            }
        }        
        return count;
    }
    
    private void dfsSearch(int i, int j, char[][] grid){
        if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] != '1'){
            return;
        }
        grid[i][j] = '0';
        dfsSearch(i + 1, j, grid);
        dfsSearch(i - 1, j, grid);
        dfsSearch(i, j + 1, grid);
        dfsSearch(i, j - 1, grid);
    }
}
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/22d746b44a30
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞