LeetCode 1254: Number of Closed Islands
LeetCode 1254 Solution Explanation
Explanation
To solve this problem, we can perform a Depth First Search (DFS) traversal on the grid to identify closed islands. We will start DFS from each cell that is a land (0) and not already visited. While performing DFS, we mark visited cells and also check if the island is closed by ensuring that it is surrounded by water (1) from all sides.
- Iterate through each cell in the grid.
- If the cell is a land (0) and not visited, start DFS from that cell.
- In DFS, mark the current cell as visited and recursively explore its neighboring cells.
- While exploring neighbors, ensure that the indices are within the bounds of the grid and the neighbor cell is also a land (0).
- If any neighbor is outside the grid bounds, it means the island is not closed.
- After DFS traversal, if the island is closed, increment the count of closed islands.
Time Complexity: O(M * N) where M is the number of rows and N is the number of columns in the grid. Space Complexity: O(M * N) due to the recursive DFS stack.
LeetCode 1254 Solutions in Java, C++, Python
class Solution {
public int closedIsland(int[][] grid) {
int rows = grid.length;
int cols = grid[0].length;
int closedIslands = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (grid[i][j] == 0 && isClosedIsland(grid, i, j)) {
closedIslands++;
}
}
}
return closedIslands;
}
private boolean isClosedIsland(int[][] grid, int i, int j) {
int rows = grid.length;
int cols = grid[0].length;
if (i < 0 || j < 0 || i >= rows || j >= cols) {
return false;
}
if (grid[i][j] == 1) {
return true;
}
grid[i][j] = 1;
boolean top = isClosedIsland(grid, i - 1, j);
boolean bottom = isClosedIsland(grid, i + 1, j);
boolean left = isClosedIsland(grid, i, j - 1);
boolean right = isClosedIsland(grid, i, j + 1);
return top && bottom && left && right;
}
}
Interactive Code Editor for LeetCode 1254
Improve Your LeetCode 1254 Solution
Use the editor below to refine the provided solution for LeetCode 1254. Select a programming language and try the following:
- Add import statements if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.
Loading editor...