664. Islands Within Islands

Two surveys of the same coastline are stored as grids of identical size: a is the old survey and b is the new one. In both, 1 means land and 0 means water, and an island is a group of land cells joined up, down, left or right. An island of b is called supported if every single one of its cells is also land in a.

Return how many islands of b are supported. Islands of a that are not covered by anything in b are irrelevant, and one large island of a may support several separate islands of b. Both grids can contain tens of thousands of cells, so aim for time linear in the number of cells.

Example 1

Input:
a = [[1,0,1],[1,1,1]], b = [[1,0,1],[0,1,0]]
Output:
3
Explanation:

The new survey has three one-cell islands and each sits on land in the old survey, so all three are supported.

Example 2

Input:
a = [[1,1,1,0],[1,0,1,0],[1,1,1,1]]b = [[1,1,0,0],[0,0,0,1],[1,0,0,1]]
Output:
2
Explanation:

The island {(0,0),(0,1)} and the island {(2,0)} are covered by old land, but the island {(1,3),(2,3)} includes (1,3) which is water in a, so the answer is 2.

Constraints

1 ≤ rows, cols ≤ 400

a and b have the same number of rows and columns

each cell is 0 or 1

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(rows*cols)
Space
O(rows*cols)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…