---
# System prepended metadata

title: 1905. Count Sub Islands
tags: [mock interview, 面試]

---

# 1905. Count Sub Islands

{%hackmd theme-dark %}
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.

![](https://i.imgur.com/nLcTGWE.png)

![](https://i.imgur.com/w7MGunX.png)

```python=

# g2 (0, 0)
# g1
def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int:
    # init
    m, n = len(grid2), len(grid2[0])
    
    # check grid 2 in grid 1
    def traverse(i, j):
        # grid is water
        ret = True
        grid2[i][j] = 0
        for ni, nj in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]:
            if 0 <= ni < m and 0 <= nj < n and grid2[ni][nj] == 1:
                if !traverse(ni, nj):
                    ret = False
        return ret and (grid1[i][j] == 1)

    
    ans = 0
    # traverse grid 2
    for i in range(m):
        for j in range(n):
            if grid2[i][j] == 1:
                # retrun is contained in grid1 or not
                contained = traverse(i, j)
                if contained:
                    ans += 1
                    
    return ans
    
    
    
    
    
    
    
    
    
```

###### tags: `mock interview` `面試`