xxxxxxxxxx
92
let grid = [
[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 7, 9]
]
function setup() {
createCanvas(400, 400);
solve();
}
function draw() {
background(255);
// solve();
drawSudoku(grid);
}
function drawSudoku(grid) {
strokeWeight(2);
line(width / 3, 0, width / 3, height);
line(width * 2 / 3, 0, width * 2 / 3, height);
line(0, height / 3, width, height / 3);
line(0, height * 2 / 3, width, height * 2 / 3);
strokeWeight(1);
for (let i = 0; i < 9; i++) {
line(i * width / 9, 0, i * width / 9, height);
line(0, i * height / 9, width, i * height / 9);
}
textAlign(CENTER, CENTER);
textSize(28);
for (let r in grid) {
row = grid[r];
for (let c in row) {
cell = row[c];
if (cell !== 0) {
text(cell, c * width / 9 + width / 18, r * height / 9 + width / 18);
}
}
}
}
function possible(x, y, n) {
for (let i = 0; i < 9; i++) {
if (grid[y][i] == n) return false
if (grid[i][x] == n) return false
}
let x0 = floor(x / 3) * 3
let y0 = floor(y / 3) * 3
for (let i = 0; i < 3; i++) {
for (let i = 0; i < 3; i++) {
if (grid[y0 + i][x0 + i] == n) return false
}
}
return true;
}
function solve() {
let find = findEmpty();
let x, y;
if (!find[0]) return true;
else {
x = find[0];
y = find[1];
}
for (i = 1; i < 10; i++) {
if (possible(x, y, i)) {
grid[y][x] = i;
if(solve()) return true;
grid[y][x] = 0;
}
}
return false;
}
function findEmpty() {
for (let y = 0; y < 9; y++) {
for (let x = 0; x < 9; x++) {
if(grid[y][x]==0){
return [x, y];
}
}
}
return null;
}