Home >Backend Development >PHP Tutorial >Count Sub Islands
1905. Count Sub Islands
Difficulty: Medium
Topics: Array, Depth-First Search, Breadth-First Search, Union Find, Matrix
You are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells.
An island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2.
Return the number of islands in grid2 that are considered sub-islands.
Example 1:
Example 2:
Constraints:
Hint:
Solution:
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 in grid1. Here's how we can implement the solution:
Let's implement this solution in PHP: 1905. Count Sub Islands
<?php /** * @param $grid1 * @param $grid2 * @return int */ function countSubIslands($grid1, $grid2) { ... ... ... /** * go to ./solution.php */ } /** * @param $grid1 * @param $grid2 * @param $i * @param $j * @param $m * @param $n * @return int|true */ function dfs(&$grid1, &$grid2, $i, $j, $m, $n) { ... ... ... /** * go to ./solution.php */ } // 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 ?>
The time complexity is (O(m times n)) where m is the number of rows and n is the number of columns. This is because we potentially visit every cell once.
This solution should work efficiently within the given constraints.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of Count Sub Islands. For more information, please follow other related articles on the PHP Chinese website!