call(back)
Algorithms & Data StructuresmediumSign in to star problems

Drop and Remove Runs in a Grid

A grid holds positive integers, with 0 for an empty cell. Repeatedly: find every horizontal or vertical run of three or more equal non-zero cells and clear all of them at the same time; then let every column's cells drop down over the empty cells. Stop when a pass clears nothing, and return the grid.

crush([[1, 1, 1]])              ->  [[0, 0, 0]]
crush([[1, 2, 3], [1, 4, 4],
       [1, 2, 3], [2, 2, 2]])   ->  [[0, 0, 0], [0, 2, 3], [0, 4, 4], [0, 2, 3]]

Hints

Hint 1

Mark cells instead of clearing them immediately: a cell can belong to both a horizontal and a vertical run, and clearing one run before scanning the other would miss cells.

Hint 2

Gravity per column is a write pointer from the bottom: copy non-zero cells downward, then fill the rest with zeros.

Asked at