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 <vector>
2#include <iostream>
3
4using namespace std;
5
6void dfs(vector<vector<int>>& grid, int x, int y, bool& isClosed) {
7 int rows = grid.size();
8 int cols = grid[0].size();
9 if (x < 0 || y < 0 || x >= rows || y >= cols) {
10 isClosed = false;
11 return;
12 }
13 if (grid[x][y] == 1 || grid[x][y] == -1) return;
14 grid[x][y] = -1;
dfs(grid, x + 1, y, isClosed);
dfs(grid, x - 1, y, isClosed);
dfs(grid, x, y + 1, isClosed);
dfs(grid, x, y - 1, isClosed);
}
int closedIsland(vector<vector<int>>& grid) {
int count = 0;
for (int i = 0; i < grid.size(); i++) {
for (int j = 0; j < grid[0].size(); j++) {
if (grid[i][j] == 0) {
bool isClosed = true;
dfs(grid, i, j, isClosed);
if (isClosed) {
count++;
}
}
}
}
return count;
}
int main() {
vector<vector<int>> 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}};
cout << closedIsland(grid) << endl;
return 0;
}
The C++ solution employs a similar DFS technique as the C solution, iterating over each cell and checking for a closed island. The grid is modified in place to mark visited cells. The boolean flag ensures we account for boundary-touching islands.
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.
Using Python's collections.deque
for the BFS queue, this solution follows similar logic to Java, marking visited nodes, and iterating via queue processing to identify closed islands.