Implement the basic elimination step of a match-three game such as Candy Crush.
You are given an m x n integer grid board, where board[i][j] is the type of candy in that cell and 0 means the cell is empty. The board shows the state right after the player's move. Restore it to a stable state by applying these steps:
-
If three or more candies of the same type are adjacent in one row or in one column, crush all of them at the same time. Their cells become empty.
-
After crushing, every candy with an empty cell below it drops until it lands on another candy or reaches the bottom. All candies drop at the same time, and no new candies enter from the top.
-
The drop can line up new runs of three or more. If it does, repeat steps 1 and 2.
-
When no run is left to crush, the board is stable. Return it.
Function Signature
def candy_crush(board: list[list[int]]) -> list[list[int]]:
Rules
-
0
marks an empty cell. Every cell of the input holds a candy (see Constraints), but the returned board can contain zeros.
-
A run is three or more equal, nonzero values in consecutive cells of one row or one column. Diagonal lines do not count.
-
In each round, first find every cell that belongs to at least one run on the current board, then crush all of those cells together. A cell that is part of both a horizontal and a vertical run is crushed once, along with both runs.
-
Gravity works per column: the candies left in a column end up at the bottom of that column in the same top-to-bottom order, with empty cells above them.
-
You may modify
board
in place and return it.
-
In the examples, row 0 is the top row and column 0 is the leftmost column.
Constraints
-
m == len(board)
-
n == len(board[i])
-
3 <= m, n <= 50
-
1 <= board[i][j] <= 2000
Examples
Input: board = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 9, 9, 9]]
Output: [[0, 0, 0, 0],
[1, 2, 3, 4],
[5, 6, 7, 8]]
The bottom row is a single run of four 9s, so all four are crushed. Every column then drops by one cell, which leaves the top row empty, and no new run forms.
Input: board = [[1, 2, 3, 4],
[2, 5, 6, 3],
[5, 5, 5, 4],
[1, 5, 2, 3]]
Output: [[0, 0, 0, 4],
[1, 0, 3, 3],
[2, 0, 6, 4],
[1, 2, 2, 3]]
Row 2 has 5, 5, 5 in columns 0 to 2, and column 1 has 5, 5, 5 in rows 1 to 3. The two runs share the cell at row 2, column 1, and all five 5s are crushed in the same round. After the drop, no run of three remains.
Input: board = [[1, 3, 5, 5, 2],
[3, 4, 3, 3, 1],
[3, 2, 4, 5, 2],
[2, 4, 4, 5, 5],
[1, 4, 4, 1, 1]]
Output: [[1, 3, 0, 0, 0],
[3, 4, 0, 5, 2],
[3, 2, 0, 3, 1],
[2, 4, 0, 5, 2],
[1, 4, 3, 1, 1]]
Column 2 has 4, 4, 4 in rows 2 to 4. Once they are crushed, the 5 and 3 above them fall to the bottom of the column, and row 3 becomes 2, 4, 5, 5, 5. A second round crushes those three 5s, and the candies above them in columns 3 and 4 fall one cell. After that, no run remains.