|
| 1 | +/** |
| 2 | + * @param {character[][]} board |
| 3 | + * @return {boolean} |
| 4 | + */ |
| 5 | +const isValidSudoku = (board) => { |
| 6 | + const rows = Array(9) |
| 7 | + .fill() |
| 8 | + .map(() => Array(9).fill(0)); |
| 9 | + const cols = Array(9) |
| 10 | + .fill() |
| 11 | + .map(() => Array(9).fill(0)); |
| 12 | + const boxes = Array(9) |
| 13 | + .fill() |
| 14 | + .map(() => Array(9).fill(0)); |
| 15 | + |
| 16 | + for (let i = 0; i < 9; i++) { |
| 17 | + for (let j = 0; j < 9; j++) { |
| 18 | + const rowCell = board[i][j]; |
| 19 | + const colCell = board[j][i]; |
| 20 | + const boxCell = board[3 * Math.floor(i / 3) + Math.floor(j / 3)][3 * (i % 3) + (j % 3)]; |
| 21 | + |
| 22 | + if (rowCell !== '.') { |
| 23 | + if (rows[i][rowCell - 1]) return false; |
| 24 | + else rows[i][rowCell - 1]++; |
| 25 | + } |
| 26 | + if (colCell !== '.') { |
| 27 | + if (cols[i][colCell - 1]) return false; |
| 28 | + else cols[i][colCell - 1]++; |
| 29 | + } |
| 30 | + if (boxCell !== '.') { |
| 31 | + if (boxes[i][boxCell - 1]) return false; |
| 32 | + else boxes[i][boxCell - 1]++; |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + console.log('ROWS: '); |
| 38 | + for (const row of rows) console.log(row.join(' ')); |
| 39 | + console.log('COLS: '); |
| 40 | + for (const col of cols) console.log(col.join(' ')); |
| 41 | + console.log('BOXES: '); |
| 42 | + for (const box of boxes) console.log(box.join(' ')); |
| 43 | + |
| 44 | + return true; |
| 45 | +}; |
| 46 | + |
| 47 | +let board = [ |
| 48 | + ['5', '3', '.', '.', '7', '.', '.', '.', '.'], |
| 49 | + ['6', '.', '.', '1', '9', '5', '.', '.', '.'], |
| 50 | + ['.', '9', '8', '.', '.', '.', '.', '6', '.'], |
| 51 | + ['8', '.', '.', '.', '6', '.', '.', '.', '3'], |
| 52 | + ['4', '.', '.', '8', '.', '3', '.', '.', '1'], |
| 53 | + ['7', '.', '.', '.', '2', '.', '.', '.', '6'], |
| 54 | + ['.', '6', '.', '.', '.', '.', '2', '8', '.'], |
| 55 | + ['.', '.', '.', '4', '1', '9', '.', '.', '5'], |
| 56 | + ['.', '.', '.', '.', '8', '.', '.', '7', '9'], |
| 57 | +]; |
| 58 | + |
| 59 | +console.log(isValidSudoku(board)); |
0 commit comments