LeetCode:Number of Islands - 统计岛屿数量

本文介绍了一种解决LeetCode 200题“统计岛屿数量”的方法。通过遍历二维数组,每发现一片陆地就递归地将其标记为已访问,并增加岛屿计数。最终返回岛屿总数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、题目名称

Number of Islands(统计岛屿数量)

2、题目地址

https://leetcode.com/problems/number-of-islands/description/

3、题目内容

英文:

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

中文:

现有一个用二维数组表示的区域,0代表水面,1代表陆地,计算区域内岛屿的数量。

4、解题方法

遍历整个区域,每找到一块陆地,统计量加一,同时将这片陆地从水域中抹去,区域遍历完毕后统计量即为所求。

/**
 * LeetCode 200 - Number of Islands
 * @文件名称 Solution.java
 * @文件作者 Tsybius2014
 * @创建时间 2017年9月26日11:10:25
 */
class Solution {
    
    /**
     * 统计岛屿数量
     * @param grid
     * @return
     */
    public int numIslands(char[][] grid) {
        
        if (grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
        
        int num = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == '1') {
                    destroyIsland(grid, i, j);
                    num++;
                }
            }
        }
        
        return num;
    }

    /**
     * 将当前陆地从区域内抹去
     * @param grid
     * @param i
     * @param j
     */
    private void destroyIsland(char[][] grid, int i, int j) {
        grid[i][j] = '0';
        if (i != 0 && grid[i -1][j] == '1') {
            destroyIsland(grid, i - 1, j);
        }
        if (i != grid.length - 1 && grid[i + 1][j] == '1') {
            destroyIsland(grid, i + 1, j);
        }
        if (j != 0 && grid[i][j - 1] == '1') {
            destroyIsland(grid, i, j - 1);
        }
        if (j != grid[0].length - 1 && grid[i][j + 1] == '1') {
            destroyIsland(grid, i, j + 1);
        }
    }

}

END

转载于:https://my.oschina.net/Tsybius2014/blog/1543557

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值