Count Sub Islands

Medium Topics Company Tags

You are given two binary grids, grid1 and grid2, with the same dimensions. A 1 represents land and a 0 represents water. An island consists of land cells joined horizontally or vertically; diagonal contact does not connect cells.

An island in grid2 is a sub-island when every one of its cells is also land in grid1. Those matching cells then belong to a single island in grid1.

Return the number of sub-islands in grid2. Count whole islands, not individual cells. If even one cell of a grid2 island lies over water in grid1, that entire island does not count.

Example 1:

Count Sub Islands, example 1: illustration of the example

Input: grid1 = [[1,1,0],[0,1,0],[1,0,1]]
grid2 = [[1,1,0],[0,1,0],[1,0,1]]

Output: 3

Explanation: Grid2 contains three islands: the connected upper-left cells and the two isolated bottom corners. Every land cell matches land in grid1, so all 3 islands count.

Example 2:

Count Sub Islands, example 2: illustration of the example

Input: grid1 = [[1,0,1]]
grid2 = [[1,1,1]]

Output: 0

Explanation: Grid2 has one island spanning all three cells. Its middle cell lies over water in grid1, so the entire island is disqualified. The matching end cells do not count separately; the answer is 0.

Example 3:

Count Sub Islands, example 3: illustration of the example

Input: grid1 = [[1,1],[1,1]]
grid2 = [[1,0],[0,1]]

Output: 2

Explanation: The two land cells in grid2 touch only diagonally, so they are two separate islands. Both lie entirely on land in grid1, giving 2 sub-islands.

Constraints:

  • Both grids have the same number of rows and columns.
  • 1 <= rows, columns <= 500
  • Every row in a grid has the same length.
  • Each cell is either 0 or 1.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.