Problem Description
We are given an m x n grid representing a Candy Crush board where each cell contains a positive integer for a type of candy, or 0 representing an empty cell. The task is to repeatedly "crush" (set to 0) candies in groups of three or more that are adjacent horizontally or vertically. Once crushed, the candies above drop down into the empty spaces, and this process is repeated until no more candies can be crushed and the board is stable.
Key Insights
- Use a simulation approach: repeatedly detect crushable candies and simulate their removal.
- Traverse horizontally and vertically to mark candies that are in groups of three or more.
- Instead of removing candies immediately, mark them for removal and update the board once for the entire pass.
- After crushing, simulate gravity by shifting non-zero candies downward in each column.
- Continue the process until no further candy crushes can be detected.
Space and Time Complexity
Time Complexity: O((mn)^2) in the worst case since each iteration includes scanning the m x n grid and then applying gravity. Space Complexity: O(mn) for maintaining additional markers or flags (or using the board itself with in-place modifications).
Solution
The approach involves iteratively scanning the board to identify candy groups that should be crushed using two passes:
- Horizontal Check – For each row, check segments of 3 consecutive candies.
- Vertical Check – For each column, check segments of 3 consecutive candies. If any candy qualifies, mark its position for crushing. After marking, update the board by turning all marked positions into 0. Then, for each column, drop down non-zero candies such that all empty cells (zeros) are at the top. Repeat this process until no group of 3 or more adjacent candies is found. Key data structures include the board array and a temporary marker (can be implicit by using signs or a separate boolean matrix) for tracking candies to crush. The algorithm ensures a stable board before returning it.