好难,没几个月就忘记了
function solveSudoku(board) {
var result = []
function backtrack(x, y) {
if (x == 9) { //打印所有
board.forEach(function (row) {
result.push(row.concat())
})
return true
} else {
if (board[x][y] == '.') {
for (var i = 1; i <= 9; i++) {//尝试在格子里面填入1-9
if (check(board, x, y, i + '')) {
board[x][y] = i + "" //处理掉0
if (backtrack((y == 8 ? x + 1 : x), (y == 8 ? 0 : y + 1))) {
return true
}
}
}
board[x][y] = '.';
} else {
if (backtrack((y == 8 ? x + 1 : x), (y == 8 ? 0 : y + 1))) {
return true
}
}
}
}
function check(board, x, y, k) {
for (var i = 0; i < 9; i++) {
//我们想在board[x][y] 中填入k, 结果在board[x][i] 或 board[i][y] 出现相同的k
if (board[x][i] == k || board[i][y] == k) {
return false;
}
}
//检查九宫格
var xx = Math.floor(x / 3)
var yy = Math.floor(y / 3)
for (var i = xx * 3; i < (xx + 1) * 3; i++) {
for (var j = yy * 3; j < (yy + 1) * 3; j++) {
if (board[i][j] == k) {
return false;
}
}
}
return true;
}
backtrack(0, 0)
// console.log(JSON.stringify(result))
return result;
}