题解 | #岛屿数量#

岛屿数量

http://www.nowcoder.com/practice/0c9664d1554e466aa107d899418e814e



public class Solution {
    /**
     * 判断岛屿数量
     * @param grid char字符型二维数组 
     * @return int整型
     */
    public int solve (char[][] grid) {
        // write code here
        if(grid == null || grid.length == 0){
            return 0;
        }
        int landNum = 0;
        for(int i = 0;i< grid.length;i++){
            for(int j = 0;j< grid[0].length;j++){
                if(grid[i][j] == '1'){
                    landNum ++;
                    //相邻的都变成0
                    dfs(grid, i , j);
                }
                
            }
        }
        return landNum;
    }
    private void dfs(char[][] grid,int r,int c){
        int row = grid.length;
        int col = grid[0].length;
        if(r < 0 || c <0 || r >= row || c >= col || grid[r][c] == '0' ){
            return;
        }
        grid[r][c] = '0';
        dfs(grid, r -1, c);
        dfs(grid, r + 1, c);
        dfs(grid, r,c - 1);
        dfs(grid, r, c+1);
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务