1905. Count Sub Islands #422
-
Topics: You are given two An island in Return the number of islands in Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We'll use the Depth-First Search (DFS) approach to explore the islands in Steps:
Let's implement this solution in PHP: 1905. Count Sub Islands <?php
/**
* @param $grid1
* @param $grid2
* @return int
*/
function countSubIslands($grid1, $grid2) {
$m = count($grid1);
$n = count($grid1[0]);
$count = 0;
for ($i = 0; $i < $m; $i++) {
for ($j = 0; $j < $n; $j++) {
if ($grid2[$i][$j] == 1 && dfs($grid1, $grid2, $i, $j, $m, $n)) {
$count++;
}
}
}
return $count;
}
/**
* @param $grid1
* @param $grid2
* @param $i
* @param $j
* @param $m
* @param $n
* @return int|true
*/
function dfs(&$grid1, &$grid2, $i, $j, $m, $n) {
if ($i < 0 || $j < 0 || $i >= $m || $j >= $n || $grid2[$i][$j] == 0) {
return true;
}
$grid2[$i][$j] = 0; // Mark the cell as visited in grid2
$isSubIsland = $grid1[$i][$j] == 1; // Check if it's a sub-island
// Explore all 4 directions
$isSubIsland &= dfs($grid1, $grid2, $i + 1, $j, $m, $n);
$isSubIsland &= dfs($grid1, $grid2, $i - 1, $j, $m, $n);
$isSubIsland &= dfs($grid1, $grid2, $i, $j + 1, $m, $n);
$isSubIsland &= dfs($grid1, $grid2, $i, $j - 1, $m, $n);
return $isSubIsland;
}
// Example usage:
// Example 1
$grid1 = [
[1,1,1,0,0],
[0,1,1,1,1],
[0,0,0,0,0],
[1,0,0,0,0],
[1,1,0,1,1]
];
$grid2 = [
[1,1,1,0,0],
[0,0,1,1,1],
[0,1,0,0,0],
[1,0,1,1,0],
[0,1,0,1,0]
];
echo countSubIslands($grid1, $grid2); // Output: 3
// Example 2
$grid1 = [
[1,0,1,0,1],
[1,1,1,1,1],
[0,0,0,0,0],
[1,1,1,1,1],
[1,0,1,0,1]
];
$grid2 = [
[0,0,0,0,0],
[1,1,1,1,1],
[0,1,0,1,0],
[0,1,0,1,0],
[1,0,0,0,1]
];
echo countSubIslands($grid1, $grid2); // Output: 2
?> Explanation:
Time Complexity:The time complexity is (O(m \times n)) where This solution should work efficiently within the given constraints. |
Beta Was this translation helpful? Give feedback.
We'll use the Depth-First Search (DFS) approach to explore the islands in
grid2
and check if each island is entirely contained within a corresponding island ingrid1
. Here's how we can implement the solution:Steps:
grid2
.grid2
: When we encounter a land cell (1
) ingrid2
, we'll use DFS to explore the entire island.grid2
, we'll check if all the corresponding cells ingrid1
are also land cells. If they are, the island is a sub-island.grid2
that meets the sub-island condition, we'll increment our sub-island count.…