在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given a 2D Return the number of closed islands. Example 1: Input: grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]] Output: 2 Explanation: Islands in gray are closed because they are completely surrounded by water (group of 1s). Example 2: Input: grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]] Output: 1 Example 3: Input: grid = [[1,1,1,1,1,1,1], [1,0,0,0,0,0,1], [1,0,1,1,1,0,1], [1,0,1,0,1,0,1], [1,0,1,1,1,0,1], [1,0,0,0,0,0,1], [1,1,1,1,1,1,1]] Output: 2 Constraints:
有一个二维矩阵 我们从一块陆地出发,每次可以往上下左右 4 个方向相邻区域走,能走到的所有陆地区域,我们将其称为一座「岛屿」。 如果一座岛屿 完全 由水域包围,即陆地边缘上下左右所有相邻区域都是水域,那么我们将其称为 「封闭岛屿」。 请返回封闭岛屿的数目。
示例 1: 输入:grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]] 输出:2 解释: 灰色区域的岛屿是封闭岛屿,因为这座岛屿完全被水域包围(即被 1 区域包围)。 示例 2: 输入:grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]] 输出:1 示例 3: 输入:grid = [[1,1,1,1,1,1,1], [1,0,0,0,0,0,1], [1,0,1,1,1,0,1], [1,0,1,0,1,0,1], [1,0,1,1,1,0,1], [1,0,0,0,0,0,1], [1,1,1,1,1,1,1]] 输出:2 提示:
Runtime: 92 ms
Memory Usage: 21.1 MB
1 class Solution { 2 func closedIsland(_ grid: [[Int]]) -> Int { 3 var grid = grid 4 for i in 0..<grid.count 5 { 6 for j in 0..<grid[i].count 7 { 8 if i == 0 || j == 0 || i == grid.count - 1 || j == grid[i].count - 1 9 { 10 fill(&grid, i, j) 11 } 12 } 13 } 14 var res:Int = 0 15 for i in 0..<grid.count 16 { 17 for j in 0..<grid[i].count 18 { 19 res += fill(&grid, i, j) > 0 ? 1 : 0 20 } 21 } 22 return res 23 } 24 25 func fill(_ g: inout [[Int]],_ i:Int,_ j:Int) -> Int 26 { 27 if i < 0 || j < 0 || i >= g.count || j >= g[i].count || g[i][j] != 0 28 { 29 return 0 30 } 31 g[i][j] = 1 32 return g[i][j] + fill(&g, i + 1, j) + fill(&g, i, j + 1) + fill(&g, i - 1, j) + fill(&g, i, j - 1) 33 } 34 }
|
请发表评论