Count Sub Islands Problem
Description
LeetCode Problem 1905.
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:

Input: 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]]
Output: 3
Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
The 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands.
Example 2:

Input: 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]]
Output: 2
Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
The 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.
Constraints:
m == grid1.length == grid2.lengthn == grid1[i].length == grid2[i].length1 <= m, n <= 500grid1[i][j]andgrid2[i][j]are either0or1.
Solution
Approach: DFS
Scan grid2. At each unvisited land cell, run a depth-first search that sinks every connected cell (sets it to 0) and tracks whether each visited cell is also land in grid1. If every cell of this island is land in grid1, it is a sub-island: count it.
Complexity: O(m n) time and O(m n) space for the recursion stack, where m x n is the grid size.
class Solution:
def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int:
def dfs(i: int, j: int) -> int:
ok = grid1[i][j]
grid2[i][j] = 0
for a, b in zip(dirs, dirs[1:]):
x, y = i + a, j + b
if 0 <= x < m and 0 <= y < n and grid2[x][y] and not dfs(x, y):
ok = 0
return ok
m, n = len(grid1), len(grid1[0])
dirs = (-1, 0, 1, 0, -1)
return sum(dfs(i, j) for i in range(m) for j in range(n) if grid2[i][j])