[LeetCode] 200. Number of Islands(岛屿的数目)

Posted Zhongju.copy()

tags:

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

Description

Given an m x n 2d grid map of ‘1‘s (land) and ‘0‘s (water), return the number of islands.
给定一个 (m imes n) 的 2D 矩形地图 grid(只包含 0(水)和 1(地)),返回岛屿的数量

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.
岛屿被水环绕,由水平和竖直方向上相邻的陆地组成。你可以假设陆地的边缘都被水环绕。

Examples

Example 1

Input: grid = [
  ["1","1","1","1","0"],
  ["1","1","0","1","0"],
  ["1","1","0","0","0"],
  ["0","0","0","0","0"]
]
Output: 1

Example 2

Input: grid = [
  ["1","1","0","0","0"],
  ["1","1","0","0","0"],
  ["0","0","1","0","0"],
  ["0","0","0","1","1"]
]
Output: 3

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 300
  • grid[i][j] is ‘0‘ or ‘1‘.

Solution

深搜,找到陆地后就往四周扩展。需要额外空间标记陆地是否都被访问过(当然本题没啥特别要求,直接在原数组上改也问题不大),代码如下:

class Solution {
    fun numIslands(grid: Array<CharArray>): Int {
        val visited = Array(grid.size) { BooleanArray(grid[0].size) }
        var result = 0

        for (i in grid.indices) {
            for (j in grid[0].indices) {
                if (grid[i][j] == ‘1‘ && !visited[i][j]) {
                    result++
                    visit(grid, i, j, visited)
                }
            }
        }

        return result
    }

    private fun visit(grid: Array<CharArray>, i: Int, j: Int, visited: Array<BooleanArray>) {
        if (i !in grid.indices || j !in grid[i].indices || grid[i][j] == ‘0‘ || visited[i][j]) {
            return
        }
        visited[i][j] = true
        visit(grid, i - 1, j, visited)
        visit(grid, i + 1, j, visited)
        visit(grid, i, j - 1, visited)
        visit(grid, i, j + 1, visited)
    }
}


以上是关于[LeetCode] 200. Number of Islands(岛屿的数目)的主要内容,如果未能解决你的问题,请参考以下文章

leetcode200 Number of Islands

Leetcode 200. Number of Islands

[leetcode-200-Number of Islands]

leetcode 200. Number of Islands

leetcode--200. Number of Islands

[LeetCode] 200. Number of Islands(岛屿的数目)