LeetCode 1905: Count Sub Islands Solution
Master LeetCode problem 1905 (Count Sub Islands), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1905. Count Sub Islands
Problem Explanation
Explanation
To solve this problem, we can perform a depth-first search (DFS) on each island in grid2 to check if it is a sub-island of any island in grid1. We will mark visited cells in grid2 during the DFS traversal. If all the cells of an island in grid2 are part of an island in grid1, then it is a sub-island. We count the number of sub-islands found.
- Perform a DFS on each cell of
grid2that is part of an island. - During the DFS traversal, mark visited cells.
- Check if each visited cell is part of an island in
grid1. - If all cells of an island in
grid2are part of an island ingrid1, increment the count of sub-islands.
Time complexity: O(mn) where m and n are the dimensions of the grids.
Space complexity: O(mn) for the visited array.
Solution Code
class Solution {
public int countSubIslands(int[][] grid1, int[][] grid2) {
int count = 0;
for (int i = 0; i < grid2.length; i++) {
for (int j = 0; j < grid2[i].length; j++) {
if (grid2[i][j] == 1) {
if (dfs(grid1, grid2, i, j)) {
count++;
}
}
}
}
return count;
}
private boolean dfs(int[][] grid1, int[][] grid2, int i, int j) {
if (i < 0 || i >= grid2.length || j < 0 || j >= grid2[0].length || grid2[i][j] == 0) {
return true;
}
if (grid1[i][j] == 0) {
return false;
}
grid2[i][j] = 0;
boolean result = true;
result &= dfs(grid1, grid2, i + 1, j);
result &= dfs(grid1, grid2, i - 1, j);
result &= dfs(grid1, grid2, i, j + 1);
result &= dfs(grid1, grid2, i, j - 1);
return result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1905 (Count Sub Islands)?
This page provides optimized solutions for LeetCode problem 1905 (Count Sub Islands) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1905 (Count Sub Islands)?
The time complexity for LeetCode 1905 (Count Sub Islands) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1905 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1905 in Java, C++, or Python.