|
| 1 | +/** |
| 2 | + * @param {character[][]} board |
| 3 | + * @return {void} Do not return anything, modify board in-place instead. |
| 4 | + */ |
| 5 | +let solveSudoku = function (board) { |
| 6 | + let rows = initTwoDimensionalArray(9) |
| 7 | + let columns = initTwoDimensionalArray(9) |
| 8 | + let grids = initTwoDimensionalArray(3) |
| 9 | + |
| 10 | + // 待处理下标队列 第一次扫描的时候记录下来 |
| 11 | + let pending = [] |
| 12 | + |
| 13 | + for (let y = 0; y < 9; y++) { |
| 14 | + for (let x = 0; x < 9; x++) { |
| 15 | + let cell = board[y][x] |
| 16 | + if (cell === ".") { |
| 17 | + // 待填充的数独格子 记录在队列中 |
| 18 | + pending.push([x, y]) |
| 19 | + continue |
| 20 | + } |
| 21 | + // 记录下当前下标 |
| 22 | + recordCell(x, y, cell) |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + let helper = (startPendingIndex) => { |
| 27 | + if (startPendingIndex === pending.length) { |
| 28 | + return true |
| 29 | + } |
| 30 | + |
| 31 | + let [x, y] = pending[startPendingIndex] |
| 32 | + |
| 33 | + for (let i = 1; i <= 9; i++) { |
| 34 | + let cur = i.toString() |
| 35 | + if (isValid(x, y, cur)) { |
| 36 | + board[y][x] = cur |
| 37 | + recordCell(x, y, cur) |
| 38 | + if (helper(startPendingIndex + 1)) { |
| 39 | + return true |
| 40 | + } else { |
| 41 | + board[y][x] = "." |
| 42 | + restoreCell(x, y, cur) |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + helper(0) |
| 49 | + |
| 50 | + function recordCell(x, y, cell) { |
| 51 | + rows[y][cell] = true |
| 52 | + columns[x][cell] = true |
| 53 | + let [gridX, gridY] = findGridIndex(x, y) |
| 54 | + if (!grids[gridY][gridX]) { |
| 55 | + grids[gridY][gridX] = new Map() |
| 56 | + } |
| 57 | + grids[gridY][gridX].set(cell, true) |
| 58 | + } |
| 59 | + |
| 60 | + function restoreCell(x, y, cell) { |
| 61 | + rows[y][cell] = false |
| 62 | + columns[x][cell] = false |
| 63 | + let [gridX, gridY] = findGridIndex(x, y) |
| 64 | + grids[gridY][gridX].set(cell, false) |
| 65 | + } |
| 66 | + |
| 67 | + function isValid(x, y, cell) { |
| 68 | + let isYConflict = rows[y][cell] |
| 69 | + let isXConflict = columns[x][cell] |
| 70 | + let [gridX, gridY] = findGridIndex(x, y) |
| 71 | + let grid = grids[gridY][gridX] |
| 72 | + let isGridConflict = grid && grid.get(cell) |
| 73 | + return !isYConflict && !isXConflict && !isGridConflict |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +function initTwoDimensionalArray(length) { |
| 78 | + let ret = [] |
| 79 | + for (let i = 0; i < length; i++) { |
| 80 | + ret.push([]) |
| 81 | + } |
| 82 | + return ret |
| 83 | +} |
| 84 | + |
| 85 | +function findGridIndex(x, y) { |
| 86 | + return [Math.floor(x / 3), Math.floor(y / 3)] |
| 87 | +} |
0 commit comments