Chain-Reaction Tile Clearing on a Grid
Arrays & HashingAuto-graded · 23 test casesLast updated
Simulate a grid game where runs of three or more equal tiles vanish together, tiles fall down, and the process repeats until the grid is stable.
Chain-Reaction Tile Clearing
You are given a 2D grid board of integers with m rows and n columns. Each positive integer is a tile type, and 0 marks an empty cell. Row 0 is the top of the grid and row m - 1 is the bottom.
The grid is processed with the following rules, repeated until nothing more can be cleared:
- Detect. A cell is selected if it belongs to a horizontal or vertical run of three or more consecutive cells that all hold the same non-zero value. A cell can be part of both a horizontal and a vertical run, so shapes such as L, T and + are possible. Empty cells (
0) are never selected. - Clear. All selected cells are emptied (set to
0) at the same moment. Detection must be completed for the entire grid before any cell is emptied. - Drop. After clearing, tiles fall straight down within their column until each one rests on the bottom edge or on another tile. The relative vertical order of the tiles in a column does not change. Empty cells end up at the top of the column.
- Repeat. Falling tiles may form new runs, so go back to step 1. Stop when step 1 selects no cells.
Return the final grid.
Task
Implement the function that takes board and returns the stable grid after all chain reactions have finished.
Constraints
1 <= m, n <= 50board[i][j]is an integer with0 <= board[i][j] <= 20000denotes an empty cell; any other value is a tile- Runs are only horizontal or vertical; diagonals do not count
- A grid with fewer than three rows or columns can still be processed; it just cannot form runs in that direction
- The result must have the same dimensions as the input
Examples
Example 1
Input: clear_tile_chains([[110, 5, 112, 113, 114], [210, 211, 5, 213, 214], [310, 311, 3, 313, 314], [410, 411, 412, 5, 414], [5, 1, 512, 3, 3], [610, 4, 1, 613, 614], [710, 1, 2, 713, 714], [810, 1, 2, 1, 1], [1, 1, 2, 2, 2], [4, 1, 4, 4, 1014]])
Output: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [110, 0, 0, 0, 114], [210, 0, 0, 0, 214], [310, 0, 0, 113, 314], [410, 0, 0, 213, 414], [610, 211, 112, 313, 614], [710, 311, 412, 613, 714], [810, 411, 512, 713, 1014]]
Example 2
Input: clear_tile_chains([[1, 1, 1], [2, 2, 2], [3, 4, 5]])
Output: [[0, 0, 0], [0, 0, 0], [3, 4, 5]]
Example 3
Input: clear_tile_chains([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Hints
Hint 1
Compute everything that should disappear in one round before changing the grid. Use a separate marker structure so a horizontal clear cannot hide a vertical run.
Hint 2
Checking every window of three consecutive cells, horizontally and vertically, is enough: longer runs are just overlapping windows. Remember to ignore windows of zeros.
Hint 3
For gravity, walk each column from the bottom up with a write pointer that receives each non-zero value, then fill whatever remains above it with zeros. Loop the whole round until no cell is cleared.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Simulate the game round by round. Each round has three phases.
- Mark. Slide a window of length three across every row and every column. If the three cells hold the same non-zero value, record all three in a separate boolean grid. Because nothing is modified during this scan, crossing runs (L, T, + shapes) are all detected correctly.
- Clear. Set every marked cell to
0. If no cell was marked, the grid is stable and we return it. - Drop. For each column, walk from the bottom to the top with a
writepointer starting at the bottom row. Every non-zero value is copied towrite, andwritemoves up by one. After the walk, all cells fromwriteupward are set to0. This is a stable compaction, so tiles keep their relative order.
Then repeat from step 1, since falling tiles may create new runs.
Why it is correct
- Simultaneous clearing. Marking is completed before clearing, so a horizontal clear cannot destroy part of a vertical run before it is noticed.
- Long runs. A run of length 3 or more is the union of its overlapping windows of three, so every cell of it gets marked.
- Zero guard. Requiring the value to be non-zero prevents empty cells from being treated as a run, which would loop forever.
- Gravity. Bottom-up stable compaction places each tile as low as possible without changing the order within the column.
- Termination. Each round that continues clears at least three tiles, so there are at most
m * n / 3rounds.
Complexity
- Time: O(m * n) per round, and at most O(m * n) rounds, so O((m * n)^2) in the worst case. Typical inputs need only a few rounds.
- Space: O(m * n) for the marker grid.
Reference solution
from typing import List
def clear_tile_chains(board: List[List[int]]) -> List[List[int]]:
rows, cols = len(board), len(board[0])
while True:
marked = [[False] * cols for _ in range(rows)]
# Horizontal windows of three
for r in range(rows):
for c in range(cols - 2):
v = board[r][c]
if v and v == board[r][c + 1] == board[r][c + 2]:
marked[r][c] = marked[r][c + 1] = marked[r][c + 2] = True
# Vertical windows of three
for c in range(cols):
for r in range(rows - 2):
v = board[r][c]
if v and v == board[r + 1][c] == board[r + 2][c]:
marked[r][c] = marked[r + 1][c] = marked[r + 2][c] = True
# Clear all marked cells simultaneously
cleared = False
for r in range(rows):
for c in range(cols):
if marked[r][c]:
board[r][c] = 0
cleared = True
if not cleared:
return board
# Gravity: compact each column toward the bottom
for c in range(cols):
write = rows - 1
for r in range(rows - 1, -1, -1):
if board[r][c] != 0:
board[write][c] = board[r][c]
write -= 1
for r in range(write, -1, -1):
board[r][c] = 0