Count Sub Islands

You are given two m x n binary matrices grid1 and grid2, where 1 is land and 0 is water. An island is a group of land cells connected 4-directionally. An island in grid2 is a sub-island if every cell of it is also land in grid1. Return the number of islands in grid2 that are sub-islands.

30:00

Count Sub Islands
medium
Free written solution
Topics
Companies

You are given two m x n binary matrices grid1 and grid2, where 1 is land and 0 is water. An island is a group of land cells connected 4-directionally. An island in grid2 is a sub-island if every cell of it is also land in grid1. Return the number of islands in grid2 that are 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
Constraints:
  • m==grid1.length==grid2.lengthm == \text{grid1.length} == \text{grid2.length}

  • n==grid1[i].length==grid2[i].lengthn == \text{grid1}[i]\text{.length} == \text{grid2}[i]\text{.length}

  • 1≤m,n≤5001 \leq m, n \leq 500

  • grid1[i][j]\text{grid1}[i][j] and grid2[i][j]\text{grid2}[i][j] are either 0 or 1

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"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]]}

An island of grid2 counts only if every one of its cells is also land in grid1. Flood each grid2 island and watch for a cell that sits on grid1 water.

grid2 islands laid over grid1

grid1 land

grid1 water

grid2 land

flooding

sub-island

on water

on stack

flood stack (top on the right)

empty

count = 0 (islands checked: 0)

Variables
VariableValue
m5
n5
land12
DepthFunction Call
Stack empty
0/24