Problem Description
We are given two m x n binary matrices grid1 and grid2. An island is defined as a group of 1's connected 4-directionally (horizontal or vertical). An island in grid2 is considered a sub-island if every cell in that island is also land (1) in grid1. The task is to count the number of such sub-islands in grid2.
Key Insights
- Traverse each island in grid2 using DFS or BFS.
- While traversing, verify each cell belongs to land in grid1.
- If any cell in the current island of grid2 is water in grid1, the whole island is disqualified.
- Mark visited cells in grid2 to avoid redundant processing.
- Process each cell in grid2 only once, leading to an efficient solution.
Space and Time Complexity
Time Complexity: O(m * n) as every cell is visited at most once. Space Complexity: O(m * n) due to recursion/stack space in the worst-case scenario.
Solution
We iterate over grid2 and whenever a cell with value 1 is found, we perform a DFS (or BFS) to scan all connected cells forming the island. During the DFS, we check if each cell in grid2 has a corresponding 1 in grid1. If not, we mark the island as invalid for being a sub-island. After visiting the entire island, if it still qualifies as a sub-island, we increment our count. We use grid2 itself to mark visited cells to avoid extra space.