#723
Medium Algorithms Candy crush
Array Two Pointers Matrix Simulation
77.3% acceptance
Mar 31, 2026
1069
548
This question is about implementing a basic elimination algorithm for Candy Crush.
Given an m x n integer array board representing the grid of candy where board[i][j] represents the type of candy. A value of board[i][j] == 0 represents that the cell 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 (i.e., the board is stable), then return the current board.
You need to perform the above rules until the board becomes stable, then return the stable board.
Solution
Rust
Time O(n * m)
Space O(n * m)
impl Solution {
pub fn candy_crush(board: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
let mut board = board;
let m = board.len();
let n = board[0].len();
loop {
let mut crush = vec![vec![false; n]; m];
let mut found = false;
// Mark horizontal
for i in 0..m {
for j in 0..n.saturating_sub(2) {
let v = board[i][j].abs();
if v != 0 && board[i][j+1].abs() == v && board[i][j+2].abs() == v {
crush[i][j] = true;
crush[i][j+1] = true;
crush[i][j+2] = true;
found = true;
}
}
}
// Mark vertical
for i in 0..m.saturating_sub(2) {
for j in 0..n {
let v = board[i][j].abs();
if v != 0 && board[i+1][j].abs() == v && board[i+2][j].abs() == v {
crush[i][j] = true;
crush[i+1][j] = true;
crush[i+2][j] = true;
found = true;
}
}
}
if !found { break; }
// Crush
for i in 0..m {
for j in 0..n {
if crush[i][j] {
board[i][j] = 0;
}
}
}
// Gravity: drop candies down
for j in 0..n {
let mut write = m as i32 - 1;
for i in (0..m).rev() {
if board[i][j] != 0 {
board[write as usize][j] = board[i][j];
if write as usize != i {
board[i][j] = 0;
}
write -= 1;
}
}
for i in 0..((write + 1) as usize) {
board[i][j] = 0;
}
}
}
board
}
}