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.*

```
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.
```

```
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.
```

`m == grid1.length == grid2.length`

`n == grid1[i].length == grid2[i].length`

`1 <= m, n <= 500`

`grid1[i][j]`

and`grid2[i][j]`

are either`0`

or`1`

.

```
class Solution:
def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int:
m, n=len(grid2), len(grid2[0])
count=0
def dfs(i,j, grid2):
# if it's outside boundary or it's water, it's island
if i<0 or j<0 or i>=m or j>=n or grid2[i][j]==0:
return 1
# if
if grid1[i][j]==0:
return 0
# mark visited cell
grid2[i][j]=0
t=dfs(i+1,j,grid2)
b=dfs(i-1,j,grid2)
l=dfs(i,j+1,grid2)
r=dfs(i,j-1,grid2)
return t and b and l and r
for i in range(m):
for j in range(n):
if grid2[i][j]==1: # check if is a sub island
check=dfs(i,j, grid2)
if check:
count+=1
return count
```

References