Greedy Algorithms8 sections · 316 units
Open in Course

Candy Crush - Implementation

The code

function candyCrush(board)
 while true
 found := false
 // Mark horizontal runs of 3+
 for row in board
 for c from 0 to cols - 2
 if |row[c]| = |row[c+1]| = |row[c+2]| != 0
 row[c], row[c+1], row[c+2] := negative
 found := true
 // Mark vertical runs similarly
 // Crush marked cells and drop
 for each column
 compact non-zero values downward
 fill top with zeros
 if not found then break
 return board

Use negative values to mark cells while preserving candy type for checking.

O((rc)2)O((rc)^2) time where r, c are dimensions. O(1)O(1) extra space.