LeetCode200 Number of Islands

LeetCode200 Number of Islands

问题来源 LeetCode200

问题描述

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:

11110
11010
11000
00000

Answer: 1

Example 2:

11000
11000
00100
00011 

Answer: 3

问题分析

这道题我的解法是递归的判断每个为“1”的方格内的元素的四周是否也为“1”,很明显会产生重复判断造成死循环,所以使用动态规划,维护一个和char[][]数组相同的数组来记录哪些为“1”的点是已经判断过的。
算法过程如下图:
算法过程
这里需要注意的一点是,因为题中需要的是独立的岛的个数,所以需要维护一个全局变量,来保存。我们可以认为一次完成一次递归就代表遍历了一个岛屿,所以每次找到新的小岛,就进行累加。完成统计

具体代码如下

代码


int res =0;
public int numIslands(char[][] grid) {
    if(grid==null||grid.length<1||grid[0].length<1) return 0;
    int m =grid.length,n = grid[0].length;
    boolean[][] dp = new boolean[m][n];
    for (int i = 0; i <m ; i++) {
        for (int j = 0; j <n ; j++) {
            if(!dp[i][j]&&grid[i][j]=='1'){
                help(grid,dp,i,j);
                res++;
            }
        }
    }
    return res;
}
void help(char[][] grid,boolean[][] dp,int i,int j){
    if(dp[i][j]) return;
    if(grid[i][j]=='1'){
        dp[i][j]=true;
        if(i>0) help(grid,dp,i-1,j);
        if(j>0) help(grid,dp,i,j-1);
        if(i<grid.length-1) help(grid,dp,i+1,j);
        if(j<grid[0].length-1) help(grid,dp,i,j+1);
    }
}

LeetCode学习笔记持续更新

GitHub地址 https://github.com/yanqinghe/leetcode

CSDN博客地址 http://blog.csdn.net/yanqinghe123/article/category/7176678

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值