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.
1#include <stdbool.h>
2
3void dfs(int** grid, int x, int y, int rows, int cols, bool* isClosed) {
The C solution uses a recursive DFS function called dfs
. For each cell containing 0
, it triggers a DFS which marks the visited islands with -1
. The boolean flag isClosed
helps determine if the island touches the boundary.
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.
public class Solution {
public int ClosedIsland(int[][] grid) {
int count = 0;
for (int i = 0; i < grid.Length; i++) {
for (int j = 0; j < grid[0].Length; j++) {
if (grid[i][j] == 0) {
if (BFS(grid, i, j)) {
count++;
}
}
}
}
return count;
}
private bool BFS(int[][] grid, int startX, int startY) {
Queue<int[]> queue = new Queue<int[]>();
queue.Enqueue(new int[] {startX, startY});
int[][] directions = new int[][] {
new int[] {1, 0},
new int[] {-1, 0},
new int[] {0, 1},
new int[] {0, -1}
};
grid[startX][startY] = -1;
bool isClosed = true;
while (queue.Count > 0) {
int[] cell = queue.Dequeue();
foreach (var dir in directions) {
int nx = cell[0] + dir[0], ny = cell[1] + dir[1];
if (nx < 0 || ny < 0 || nx >= grid.Length || ny >= grid[0].Length) {
isClosed = false;
} else if (grid[nx][ny] == 0) {
grid[nx][ny] = -1;
queue.Enqueue(new int[] {nx, ny});
}
}
}
return isClosed;
}
}
C# uses a Queue
for non-recursive BFS traversal, checking boundaries directly during each visit to manage 0-cell expansions and boundary edge checks efficiently.