Cascading Tile Crush on a Grid
Arrays & HashingAuto-graded · 19 test casesLast updated
Simulate a tile-crush game: mark all runs of 3+ equal tiles, clear them, drop tiles with gravity, and repeat until stable, counting removed tiles.
Cascading Tile Crush on a Grid
You are given a rectangular grid of tiles. Each tile is a positive integer that identifies its kind. The value 0 means the cell is empty. Simulate the following crush-and-drop process until the grid is stable, then report the final grid and how many tiles were removed in total.
One round
- Mark. Look at every maximal horizontal run and every maximal vertical run of equal, non-zero tiles. If a run has length 3 or more, every tile in it is marked. A tile in both a qualifying horizontal run and a qualifying vertical run (an L, T or plus shape) is marked once. Diagonal neighbours never form runs. Empty cells (
0) never match each other. - Clear. Only after all marking is finished, set every marked cell to
0. All removals in a round happen simultaneously, so clearing one run must not change which other runs qualify in the same round. - Drop. In each column independently, the surviving non-zero tiles fall straight down, keeping their relative top-to-bottom order. The column's empty cells end up at the top.
- Repeat. Start a new round on the resulting grid. Stop when a round marks no tiles.
The total count is the number of distinct cells cleared across all rounds. A cell that is in two runs in the same round counts once.
Task
Write a function that takes the grid and returns a two-element list [final_grid, total_removed], where final_grid is the stable grid (a list of rows) and total_removed is an integer.
Details to get right
- Do not modify the input grid. Return a new grid.
- Gravity is applied only after a round that removed something. If the first round marks nothing, return the grid exactly as given, with a count of
0, even if it already contains0cells that are not at the top of their columns. - If the grid has no rows, return
[[], 0]. - If rows are empty (zero columns), return a copy of the grid and
0.
Constraints
0 <= m, n <= 50, wheremis the number of rows andnthe number of columns. All rows have the same length.- Each cell is an integer in the range
0to10^4, where0means empty. - The process always ends, since each productive round removes at least three tiles.
Examples
Example 1
Input: crush_board([[1, 1, 1], [2, 3, 2], [2, 2, 2]])
Output: [[[0, 0, 0], [0, 0, 0], [2, 3, 2]], 6]
Example 2
Input: crush_board([[1, 2, 3], [1, 2, 3], [1, 2, 3]])
Output: [[[0, 0, 0], [0, 0, 0], [0, 0, 0]], 9]
Example 3
Input: crush_board([[1, 2, 1, 2], [2, 1, 2, 1], [1, 2, 1, 2], [2, 1, 2, 1]])
Output: [[[1, 2, 1, 2], [2, 1, 2, 1], [1, 2, 1, 2], [2, 1, 2, 1]], 0]
Hints
Hint 1
Never clear cells while you are still scanning. Record matches in a separate boolean grid first, otherwise an L or T shape can lose part of its run.
Hint 2
To find runs, walk along each row and each column, extending a pointer while the value stays the same. If the run length is at least 3, mark the whole run, then jump past it. Count marked cells, not run lengths, so overlaps are counted once.
Hint 3
For gravity, process each column from the bottom up with a write pointer: copy each non-zero value to the write position and move the pointer up, then fill what is left above with zeros. Loop until a round marks nothing.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each round has three separate phases: mark, clear, drop. Rounds repeat until one marks nothing.
Mark first, clear later. Matches are recorded in a boolean grid of the same size, and nothing is cleared until every row and column has been scanned. This makes removals simultaneous. If you cleared as you scanned, removing the horizontal arm of an L shape could shorten its vertical arm below three, and the shape would be handled wrongly.
Finding runs. For each row, walk left to right. From position c, extend end while the next cell holds the same non-zero value. If end - c >= 3, mark every cell in [c, end). Then continue from end. Do the same down each column. Because the walk extends to the end of the run, runs of length 4, 5 or more are captured entirely. Empty cells are skipped, so zeros never match. Diagonals are never examined.
Counting. The count is the number of True cells in the marked grid. An intersection cell (the corner of an L or the centre of a plus) is marked by both scans but counted once. Adding up run lengths instead would double-count it.
Gravity. After setting marked cells to 0, compact each column independently. Walk from the bottom row upward with a write pointer that starts at the last row. Each non-zero value is copied to write, and write moves up by one. Everything above the final write position is then filled with zeros. This keeps the surviving tiles in order and pushes empties to the top.
Termination. Gravity never creates new non-zero tiles, and each productive round removes at least 3 of them. So there are at most mn/3 productive rounds, plus one last round that confirms stability.
Why it is correct
- Detection finds every maximal horizontal and vertical run of length at least 3, so a cell is marked exactly when the rules say it should be.
- All marking happens before any clearing, so removals are simultaneous.
- Gravity only moves tiles straight down within their column, and the compaction preserves their order.
- Gravity is the only thing that can create new runs, and the loop rescans after every drop, so cascades are handled.
- If the first round marks nothing, the loop exits before any gravity runs. A grid that already has floating zeros is therefore returned unchanged, as required.
Complexity
Let m be the number of rows and n the number of columns.
- Per round:
O(mn)for scanning, counting, clearing and compaction. - Number of rounds: at most about
mn/3 + 1. - Time:
O((mn)^2)in the worst case, usually much faster because cascades are short. - Space:
O(mn)for the grid copy and the marked grid.
Reference solution
from typing import List
def crush_board(grid: List[List[int]]) -> List:
cells = [row[:] for row in grid]
rows = len(cells)
if rows == 0:
return [[], 0]
cols = len(cells[0])
if cols == 0:
return [[row[:] for row in cells], 0]
total_removed = 0
while True:
marked = [[False] * cols for _ in range(rows)]
# Horizontal runs
for r in range(rows):
c = 0
while c < cols:
v = cells[r][c]
if v == 0:
c += 1
continue
end = c + 1
while end < cols and cells[r][end] == v:
end += 1
if end - c >= 3:
for j in range(c, end):
marked[r][j] = True
c = end
# Vertical runs
for c in range(cols):
r = 0
while r < rows:
v = cells[r][c]
if v == 0:
r += 1
continue
end = r + 1
while end < rows and cells[end][c] == v:
end += 1
if end - r >= 3:
for i in range(r, end):
marked[i][c] = True
r = end
count = sum(1 for r in range(rows) for c in range(cols) if marked[r][c])
if count == 0:
break
total_removed += count
for r in range(rows):
for c in range(cols):
if marked[r][c]:
cells[r][c] = 0
# Gravity per column
for c in range(cols):
write = rows - 1
for r in range(rows - 1, -1, -1):
if cells[r][c] != 0:
cells[write][c] = cells[r][c]
write -= 1
while write >= 0:
cells[write][c] = 0
write -= 1
return [cells, total_removed]