let arr = [
[3, 0, 6, 5, 0, 8, 4, 0, 0],
[5, 2, 0, 0, 0, 0, 0, 0, 0],
[0, 8, 7, 0, 0, 0, 0, 3, 1],
[0, 0, 3, 0, 1, 0, 0, 8, 0],
[9, 0, 0, 8, 6, 3, 0, 0, 5],
[0, 5, 0, 0, 9, 0, 6, 0, 0],
[1, 3, 0, 0, 0, 0, 2, 5, 0],
[0, 0, 0, 0, 0, 0, 0, 7, 4],
[0, 0, 5, 2, 0, 6, 3, 0, 0]
]
let pos = {};
let rem = {};
let graph = {};
function
printMatrix() {
for
(let i = 0; i < 9; i++) {
for
(let j = 0; j < 9; j++) {
process.stdout.write(arr[i][j]+
" "
);
}
console.log();
}
}
function
is_safe(x, y) {
let key = arr[x][y];
for
(let i = 0; i < 9; i++) {
if
(i !== y && arr[x][i] === key) {
return
false
;
}
if
(i !== x && arr[i][y] === key) {
return
false
;
}
}
let r_start = Math.floor(x / 3) * 3;
let r_end = r_start + 3;
let c_start = Math.floor(y / 3) * 3;
let c_end = c_start + 3;
for
(let i = r_start; i < r_end; i++) {
for
(let j = c_start; j < c_end; j++) {
if
(i !== x && j !== y && arr[i][j] === key) {
return
false
;
}
}
}
return
true
;
}
function
fill_matrix(k, keys, r, rows) {
for
(let c of graph[keys[k]][rows[r]]) {
if
(arr[rows[r]] > 0) {
continue
;
}
arr[rows[r]] = keys[k];
if
(is_safe(rows[r], c)) {
if
(r < rows.length - 1) {
if
(fill_matrix(k, keys, r + 1, rows)) {
return
true
;
}
else
{
arr[rows[r]] = 0;
continue
;
}
}
else
{
if
(k < keys.length - 1) {
if
(fill_matrix(k + 1, keys, 0, list(graph[keys[k + 1]].keys()))) {
return
true
;
}
else
{
arr[rows[r]] = 0;
continue
;
}
}
return
true
;
}
}
arr[rows[r]] = 0;
}
return
false
;
}
function
build_pos_and_rem() {
for
(let i = 0; i < 9; i++) {
for
(let j = 0; j < 9; j++) {
if
(arr[i][j] > 0) {
if
(!pos.hasOwnProperty(arr[i][j])) {
pos[arr[i][j]] = [];
}
pos[arr[i][j]].push([i, j]);
if
(!rem.hasOwnProperty(arr[i][j])) {
rem[arr[i][j]] = 9;
}
rem[arr[i][j]] -= 1;
}
}
}
for
(let i = 1; i < 10; i++) {
if
(!pos.hasOwnProperty(i)) {
pos[i] = [];
}
if
(!rem.hasOwnProperty(i)) {
rem[i] = 9;
}
}
}
function
build_graph() {
for
(let [k, v] of Object.entries(pos)) {
if
(!graph.hasOwnProperty(k)) {
graph[k] = {};
}
let row = [...Array(9).keys()];
let col = [...Array(9).keys()];
for
(let cord of v) {
row.splice(row.indexOf(cord[0]), 1);
col.splice(col.indexOf(cord[1]), 1);
}
if
(row.length === 0 || col.length === 0) {
continue
;
}
for
(let r of row) {
for
(let c of col) {
if
(arr[r] === 0) {
if
(!graph[k].hasOwnProperty(r)) {
graph[k][r] = [];
}
graph[k][r].push(c);
}
}
}
}
}
build_pos_and_rem();
rem = Object.fromEntries(Object.entries(rem).sort((a, b) => a[1] - b[1]));
build_graph();
let key_s = Object.keys(rem);
fill_matrix(0, key_s, 0, Object.keys(graph[key_s[0]]));
printMatrix();