|
| 1 | +/** |
| 2 | + * @param {number[][]} board |
| 3 | + * @return {number[][]} |
| 4 | + */ |
| 5 | +const candyCrush = function (board) { |
| 6 | + while (true) { |
| 7 | + let moreToCrush = false |
| 8 | + for (let i = 0; i < board.length; i++) { |
| 9 | + for (let j = 0; j < board[0].length; j++) { |
| 10 | + if (board[i][j] > 0) { |
| 11 | + moreToCrush = |
| 12 | + flagForCrush(board, i, j, board[i][j], 0, true, false) || |
| 13 | + moreToCrush |
| 14 | + moreToCrush = |
| 15 | + flagForCrush(board, i, j, board[i][j], 0, false, true) || |
| 16 | + moreToCrush |
| 17 | + } |
| 18 | + } |
| 19 | + } |
| 20 | + if (!moreToCrush) break |
| 21 | + crush(board) |
| 22 | + inflictGravity(board) |
| 23 | + } |
| 24 | + return board |
| 25 | +} |
| 26 | +const flagForCrush = function (board, i, j, target, count, right, down) { |
| 27 | + if ( |
| 28 | + j === board[0].length || |
| 29 | + i === board.length || |
| 30 | + Math.abs(board[i][j]) !== Math.abs(target) |
| 31 | + ) { |
| 32 | + return count >= 3 |
| 33 | + } |
| 34 | + |
| 35 | + let shouldFlagIndexRight = flagForCrush( |
| 36 | + board, |
| 37 | + i, |
| 38 | + j + 1, |
| 39 | + target, |
| 40 | + right ? count + 1 : 1, |
| 41 | + true, |
| 42 | + false |
| 43 | + ) |
| 44 | + let shouldFlagIndexDown = flagForCrush( |
| 45 | + board, |
| 46 | + i + 1, |
| 47 | + j, |
| 48 | + target, |
| 49 | + down ? count + 1 : 1, |
| 50 | + false, |
| 51 | + true |
| 52 | + ) |
| 53 | + |
| 54 | + if ((shouldFlagIndexRight && right) || (shouldFlagIndexDown && down)) { |
| 55 | + board[i][j] = -Math.abs(board[i][j]) |
| 56 | + return true |
| 57 | + } |
| 58 | + |
| 59 | + return false |
| 60 | +} |
| 61 | +const crush = function (board) { |
| 62 | + for (let i = 0; i < board.length; i++) { |
| 63 | + for (let j = 0; j < board[0].length; j++) { |
| 64 | + if (board[i][j] < 0) board[i][j] = 0 |
| 65 | + } |
| 66 | + } |
| 67 | +} |
| 68 | +const inflictGravity = function (board) { |
| 69 | + for (let j = 0; j < board[0].length; j++) { |
| 70 | + let st = board.length - 1 |
| 71 | + let end = board.length - 2 |
| 72 | + while (end >= 0) { |
| 73 | + if (board[st][j] === 0 && board[end][j] !== 0) { |
| 74 | + let temp = board[st][j] |
| 75 | + board[st][j] = board[end][j] |
| 76 | + board[end][j] = temp |
| 77 | + st-- |
| 78 | + } else if (board[st][j] !== 0) { |
| 79 | + st-- |
| 80 | + } |
| 81 | + end-- |
| 82 | + } |
| 83 | + } |
| 84 | +} |
0 commit comments