admin 管理员组

文章数量: 887007

iOS LeetCode ☞ 岛屿数量

给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。

岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。

此外,你可以假设该网格的四条边均被水包围。

示例 1:

输入:grid = [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]
]
输出:1

示例 2:

输入:grid = [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]
]
输出:3

提示:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 300
  • grid[i][j] 的值为 '0''1'

解题思路

我们可以将二维网格看成一个无向图,竖直或水平相邻的 1 之间有边相连。

为了求出岛屿的数量,我们可以扫描整个二维网格。如果一个位置为 1,则以其为起始节点开始进行深度优先搜索。在深度优先搜索的过程中,每个搜索到的 1 都会被重新标记为 0

最终岛屿的数量就是我们进行深度优先搜索的次数。

代码

	// 200. 岛屿数量func numIslands(_ grid: [[Character]]) -> Int {var grid = gridfunc dfs(_ r: Int, _ c: Int) {let nr = grid.countlet nc = grid[0].countif r < 0 || c < 0 || r >= nr || c >= nc || grid[r][c] == "0" {return}grid[r][c] = "0"dfs(r - 1, c)dfs(r + 1, c)dfs(r, c - 1)dfs(r, c + 1)}if grid.count == 0 {return 0}let nr = grid.count, nc = grid[0].countvar numIslands = 0for r in 0..<nr {for c in 0..<nc {if grid[r][c] == "1" {numIslands += 1dfs(r, c)}}}return numIslands}

本文标签: iOS LeetCode ☞ 岛屿数量