题解 | #Sudoku#
Sudoku
https://www.nowcoder.com/practice/78a1a4ebe8a34c93aac006c44f6bf8a1
const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;
void (async function () {
const arr = [];
while ((line = await readline())) {
arr.push(line.split(" ").map((item) => parseInt(item)));
}
const vaild = (i, j, v) => {
for (let m = 0; m < 9; m++) {
if (arr[i][m] == v && m != j) {
return false;
}
if (arr[m][j] == v && m != i) {
return false;
}
}
for (
let m = Math.floor(i / 3) * 3;
m < Math.floor(i / 3 + 1) * 3;
m++
) {
for (
let n = Math.floor(j / 3) * 3;
n < Math.floor(j / 3 + 1) * 3;
n++
) {
if (arr[m][n] == v && !(m == i && n == j)) {
return false;
}
}
}
return true;
};
const f = (i, j) => {
if(i>=9||j>=9){
return true;
}
if (arr[i][j]) {
return f(i + Math.floor((j + 1) / 9), (j + 1) % 9);
}
for (let m = 1; m <= 9; m++) {
if (vaild(i, j, m)) {
arr[i][j] = m;
if (f(i + (j + 1 >= 9 ? 1 : 0), (j + 1) % 9)) {
return true;
}
}
}
arr[i][j] = 0;
return false;
};
f(0, 0);
console.log(arr.map((item) => item.join(" ")).join("\n"));
})();
查看7道真题和解析