1254. Number of Closed Islands (M)

https://leetcode.com/problems/number-of-closed-islands/

Given a 2D grid consists of 0s (land) and 1s (water). An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s.

Return the number of closed islands.

Example 1:

Example 2:

Example 3:

Constraints:

  • 1 <= grid.length, grid[0].length <= 100

  • 0 <= grid[i][j] <=1

Solution:

Version 1: DFS

那么如何判断「封闭岛屿」呢?其实很简单,把LeetCode 200 中那些靠边的岛屿排除掉,剩下的不就是「封闭岛屿」了吗

有了这个思路,就可以直接看代码了,注意这题规定 0 表示陆地,用 1 表示海水:

只要提前把靠边的陆地都淹掉,然后算出来的就是封闭岛屿了。

PS:处理这类岛屿题目除了 DFS/BFS 算法之外,Union Find 并查集算法也是一种可选的方法,前文 Union Find 算法运用 就用 Union Find 算法解决了一道类似的问题。

Version 2: Union Find

Last updated

Was this helpful?