Skip to content
BytePatterns

Islands After Each Land Drop

MediumUnion-Find#union-find#online-connectivity#grid~30m

Problem

A grid with m rows and n columns starts as all water. You are given a list of positions [row, col], and each one turns that cell into land, in order. Land cells that touch up, down, left or right belong to the same island. After each position, report how many islands there are. A position can appear more than once, and turning land into land changes nothing.

Examples

Input:  m = 3, n = 3, positions = [[0, 0], [0, 1], [1, 2], [2, 1]]
Output: [1, 1, 2, 3]
Why:    [0, 1] joins [0, 0], while [1, 2] and [2, 1] touch nothing
Input:  m = 2, n = 2, positions = [[0, 0], [1, 1], [0, 1]]
Output: [1, 2, 1]
Why:    [0, 1] touches both earlier cells and merges two islands into one
Input:  m = 1, n = 1, positions = [[0, 0], [0, 0]]
Output: [1, 1]
Why:    edge case, the repeated position is already land

Hints

0 / 3

Stuck on the idea rather than the code? Path Compression covers it.