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 ☞ 岛屿数量
版权声明:本文标题:iOS LeetCode ☞ 岛屿数量 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.freenas.com.cn/jishu/1732351422h1533177.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论