Sponsored
Sponsored
The grid can be viewed as a graph where each cell is a node connected to its four possible neighbors. To identify closed islands, we can use a DFS approach starting from any cell containing 0
(cell of land). This DFS should mark the entire island by changing those 0
s to a visited flag, such as -1
. During the traversal, if any part of the island reaches the grid's boundary, it cannot be a closed island.
For each unvisited 0
, if it forms a complete island (i.e., it does not reach the boundary), we increment the closed island count. We examine cells systematically, ensuring that all possible islands are accounted for.
Time Complexity: O(m * n), where m
is the number of rows, and n
is the number of columns. Each cell is visited once.
Space Complexity: O(m * n) due to the recursion stack.
1var closedIsland = function(grid) {
2 const dfs = (x, y) => {
3 if (x < 0
JavaScript's implementation adopts a closure for the DFS function, marking traversed islands and ensuring to verify edge connections to correctly increment the closed island count.
This approach employs BFS to traverse the islands. By leveraging a queue, we can iteratively explore all 0
-connected land cells starting from each unvisited land cell. If during any BFS iteration, we find ourselves at the boundary or edge of the grid, the ongoing island is not closed.
Using BFS here can make iterative exploration more intuitive and can be preferred in languages where managing stacks explicitly is a common challenge, although the core logic of edge-checking remains similar.
Time Complexity: O(m * n), where m
is the number of rows, and n
is the number of columns.
Space Complexity: O(m + n) due to the queue memory usage during BFS.
The C solution employs a manual queue for BFS due to language constraints. The grid modifies in place, leveraging BFS to spread through each island starting from unvisited land cells.