Number of Islands II

IF
AlgoAxiomStaff Engineers
JSTS
Hard20 mins

You are given an empty 2D binary grid of size m x n. The grid represents a map where 0s represent water and 1s represent land. Initially, all the cells of the grid are water cells (i.e., all cells are 0s).

We may perform an addLand operation which turns the water at position into a land. You are given an array positions where positions[i] = [ri, ci] is the position (ri, ci) at which we should operate the ith addLand operation.

Return an array of integers answer where answer[i] is the number of islands after turning the cell (ri, ci) into a land.

An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically.

Examples

Example 1:

Input: m = 3, n = 3, positions = [[0,0],[0,1],[1,2],[2,1]]

Output: [1,1,2,3]

Explanation:

  • Add land at (0,0): 1 island
  • Add land at (0,1): still 1 island (connected to (0,0))
  • Add land at (1,2): 2 islands (not connected to others)
  • Add land at (2,1): 3 islands

Example 2:

Input: m = 1, n = 1, positions = [[0,0]]

Output: [1]

Constraints

  • 1 <= m, n, positions.length <= 10^4
  • 1 <= m * n <= 10^4
  • positions[i].length == 2
  • 0 <= ri < m
  • 0 <= ci < n
Source: Union Find pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle