// 验证数独是否有效的函数 functionisValidSudoku(board) { const boxes = Array(9).fill().map(() =>newSet()); for (let i = 0; i < 9; i++) { let rolSet = newSet() let colSet = newSet() for (let j = 0; j < 9; j++) { if (board[i][j] !== '.') { if (rolSet.has(board[i][j])) returnfalse rolSet.add(board[i][j]) } if (board[j][i] !== '.') { if (colSet.has(board[j][i])) returnfalse colSet.add(board[j][i]) } let boxIndex = Math.floor(i / 3) * 3 + Math.floor(j / 3) if (board[i][j] !== '.') { if (boxes[boxIndex].has(board[i][j])) returnfalse boxes[boxIndex].add(board[i][j]) } } } returntrue }
// 寻找空白格 functionfindEmpty(board) { for (let i = 0; i < 9; i++) { for (let j = 0; j < 9; j++) { if (board[i][j] === '.') { return [i, j] } } } }
// 递归求解数独 functionsolveSudoku(board) { let empty = findEmpty(board) if (!empty) { // 完成 return board } for (let i = 1; i <= 9; i++) { board[empty[0]][empty[1]] = String(i) if (isValidSudoku(board)) { let result = solveSudoku(board) // 递归解决剩余的格子 if (result) return result } board[empty[0]][empty[1]] = '.' } returnfalse }