码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-11-23 12:25:21      阅读:3      评论:0      收藏:0      [点我收藏+]

标签:inpu   solution   private   traints   union   size   http   boolean   grid   

Description

Given an m x n 2d grid map of ‘1‘s (land) and ‘0‘s (water), return the number of islands.
给定一个 \(m \times 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(岛屿的数目)

标签:inpu   solution   private   traints   union   size   http   boolean   grid   

原文地址:https://www.cnblogs.com/zhongju/p/14003430.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!