Skip to main content

723. Candy Crush

https://leetcode.com/problems/candy-crush/

Python

class Solution:
def candyCrush(self, board: List[List[int]]) -> List[List[int]]:
while self.crash(board):
self.drop(board)

return board

def crash(self, board) -> bool:
m = len(board)
n = len(board[0])

should_crash = set()
for row in range(m):
for col in range(n):
if board[row][col] == 0:
continue

if row > 1 and board[row][col] == board[row-1][col] == board[row-2][col]:
should_crash.add((row, col))
should_crash.add((row-1, col))
should_crash.add((row-2, col))

if col > 1 and board[row][col] == board[row][col-1] == board[row][col-2]:
should_crash.add((row, col))
should_crash.add((row, col-1))
should_crash.add((row, col-2))

if should_crash:
for row, col in should_crash:
board[row][col] = 0
return True

return False

def drop(self, board):
m = len(board)
n = len(board[0])

for col in range(n):
idx = len(board)-1
for row in range(m-1, -1, -1):
if board[row][col]>0:
board[idx][col] = board[row][col]
idx -= 1

for row in range(idx+1):
board[row][col] = 0

Javascript

var candyCrush = function(board) {
let crush = false;
// row
for (let r = 0; r < board.length; r++) {
for (let c = 0; c < board[r].length - 2; c++) {
const target = Math.abs(board[r][c]);
const allEqual = (target === Math.abs(board[r][c + 1])) && (target === Math.abs(board[r][c + 2]));
if (board[r][c] !== 0 && allEqual) {
board[r][c] = board[r][c + 1] = board[r][c + 2] = -target;
crush = true;
}
}
}

// col
for (let c = 0; c < board[0].length; c++) {
for (let r = 0; r < board.length - 2; r++) {
const target = Math.abs(board[r][c]);
const allEqual = (target === Math.abs(board[r + 1][c])) && (target === Math.abs(board[r + 2][c]));

if (board[r][c] !== 0 && allEqual) {
board[r][c] = board[r + 1][c] = board[r + 2][c] = -target;
crush = true;
}
}
}

for (let c = 0; c < board[0].length; c++) {
let tmp = board.length - 1;
for (let r = board.length - 1; r >= 0; r--) {
if (board[r][c] > 0) {
board[tmp--][c] = board[r][c]
}
}
while (tmp >= 0) board[tmp--][c] = 0;
}
// console.log(board)

if (crush) return candyCrush(board);
else return board;
};