Problem 577166 · medium · Phase 05 Advanced Algorithms & Graphs

Islands After Each Landfill

union-find · grids · online connectivity

A harbour is a rows x cols grid that starts as open water. Engineers dump landfill one cell at a time: fills is a list of [r, c] positions (0 <= r < rows, 0 <= c < cols), processed in order, each turning that cell into land. A cell may appear more than once; filling land again changes nothing.

An island is a maximal group of land cells connected horizontally or vertically (not diagonally). Return a list with the number of islands after each fill.

Examples

Input:  rows = 3, cols = 3, fills = [[0, 0], [0, 1], [1, 2], [2, 1], [1, 1]]
Output: [1, 1, 2, 3, 1]
Explanation: the last fill touches (0, 1), (1, 2) and (2, 1), merging all three islands.

Input:  rows = 1, cols = 1, fills = [[0, 0], [0, 0]]
Output: [1, 1]

Input:  rows = 2, cols = 2, fills = [[0, 0], [1, 1], [0, 1]]
Output: [1, 2, 1]

Constraints

  • 1 <= rows, cols <= 10**4, rows * cols <= 10**4, 0 <= len(fills) <= 10**4
  • Target: O(rows * cols + F * alpha(rows * cols)) time.

Goals

  • Maintain a component count while cells are added one at a time
  • Map 2D grid cells to union-find indices
Starting Python…