723 Candy Crush
723. Candy Crush
1. Question
This question is about implementing a basic elimination algorithm for Candy Crush.
Given a 2D integer arrayboard
representing the grid of candy, different positive integersboard[i][j]
represent different types of candies. A value ofboard[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 astable stateby 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:
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, 2000].
2. Implementation
(1) Two Pointers
思路: Two Pointers的思想指体现在Candy Drop的时候,对每一列,将非零的数往下drop,而将0往上移。
3. Time & Space Complexity
时间复杂度O(mn), 空间复杂度O(mn)
Last updated