Visualize

Pattern visualizer

Most Stones Removed with Same Row or Column

Never simulate the removals. Treat every row index and every column index as its own node, and let each stone be one edge joining its row-node to its column-node — two stones can always be chained down to one survivor exactly when their nodes sit in the same connected piece. A union-find over those row/column nodes finds every piece in one pass over the stones, and a piece of k stones always yields k - 1 removable ones, so the answer is simply the stone count minus the number of pieces. Animated on: 6 stones at (0,0), (0,1), (1,0), (1,2), (2,1), (2,2) — a stone can be removed only while another stone still shares its row or column. What is the maximum number removable?.

Bipartite row/column union-find: stones - connected components

time O(N * a(N))space O(N)step 1 / 9

One node per row, one per column

line 1

6 stones sit on 3 rows and 3 columns. Instead of graphing stone-to-stone, make each row and each column its own node: stone (r, c) becomes one edge between row r and column c. Two stones end up removable together exactly when their nodes land in the same connected piece.

Pseudocode
1FUNCTION removeStones(stones):
2 FOR EACH [r, c] IN stones
3 UNION(ROW(r), COL(c))
4 roots <- EMPTY SET
5 FOR EACH [r, c] IN stones
6 ADD FIND(ROW(r)) TO roots
7 RETURN LENGTH(stones) - SIZE(roots)

← / → step · space play · Home restart

Where to practice Graph