/**
* @param {character[][]} board
* @return {void} Do not return anything, modify board in-place instead.
*/
var solveSudoku = function (board) {
const canMatrix = new Array(9).fill([]).map(() => new Array(9).fill(false));
let x = null;
let y = null;
for (let i = 8; i >= 0; i--) {
for (let j = 8; j >= 0; j--) {
if (board[i][j] === '.') {
canMatrix[i][j] = true;
board[i][j] = 0;
x = i;
y = j;
} else {
board[i][j] = Number(board[i][j]);
}
}
}
if (x === null) {
return board;
}
// 判断是否冲突
const hasConflict = function (i, j, val) {
for (let e1 = 0; e1 < 9; e1++) {
if ((e1 !== j && val === board[i][e1]) || (e1 !== i && val === board[e1][j])) {
return false;
}
}
const t1 = Math.floor(i / 3) * 3;
const t2 = Math.floor(j / 3) * 3;
for (let p1 = t1; p1 < t1 + 3; p1++) {
for (let p2 = t2; p2 < t2 + 3; p2++) {
if (val === board[p1][p2] && p1 !== i && p2 !== j) {
return false;
}
}
}
return true;
};
// 获取下一个
const getXY = function (x, y, direction) {
if (direction) {
if (y === 8) {
x = x + 1;
y = 0;
} else {
y = y + 1;
}
} else if (y === 0) {
x = x - 1;
y = 8;
} else {
y = y - 1;
}
return {
x: x,
y: y
};
};
// 递归
const fill = function (x, y, direction) {
if (x > 8) {
return;
}
if (canMatrix[x][y]) {
let r = 0;
for (let i = board[x][y] + 1; i <= 9; i++) {
if (hasConflict(x, y, i)) {
r = i;
break;
}
}
board[x][y] = r;
if (r === 0) {
const obj = getXY(x, y, false);
fill(obj.x, obj.y, false);
} else {
const obj = getXY(x, y, true);
fill(obj.x, obj.y, true);
}
} else {
const obj = getXY(x, y, direction);
fill(obj.x, obj.y, direction);
}
};
fill(x, y, true);
for (let i = 8; i >= 0; i--) {
for (let j = 8; j >= 0; j--) {
board[i][j] = String(board[i][j]);
}
}
return board;
};