Description
This question is about implementing a basic elimination algorithm for Candy Crush.
Given a 2D integer array board representing the grid of candy, different positive integers board[i][j] represent different types of candies. A value of board[i][j] = 0 represents that the cell at position (i, j) is empty. The given board represents the state of the game following the player’s move. Now, you need to restore the board to a stable state by crushing candies according to the following rules:
- If three or more candies of the same type are adjacent vertically or horizontally, “crush” them all at the same time - these positions become empty.
- After crushing all candies simultaneously, if an empty space on the board has candies on top of itself, then these candies will drop until they hit a candy or bottom at the same time. (No new candies will drop outside the top boundary.)
- After the above steps, there may exist more candies that can be crushed. If so, you need to repeat the above steps.
- If there does not exist more candies that can be crushed (ie. the board is stable), then return the current board.
You need to perform the above rules until the board becomes stable, then return the current board.
Example
1 | Input: |
Explanation:
Note:
- The length of board will be in the range [3, 50].
- The length of board[i] will be in the range [3, 50].
- Each board[i][j] will initially start as an integer in the range [1, 200
Solution
The idea is to traverse the entire matrix again and again to remove crush until no crush can be found.
For each traversal of the matrix, we only check two directions, rightward and downward. There is no need to check upward and leftward because they would have been checked from previous cells.
For each cell, if there are at least three candies of the same type rightward or downward, set them all to its negative value to mark them.
After each traversal, we need to remove all those negative values by setting them to 0, then let the rest drop down to their correct position. A easy way is to iterate through each column, for each column, move positive values to the bottom then set the rest to 0.
1 | class Solution { |