I've written the following recursive code, for solving a sudoku puzzle.
grid: a global matrix, representing the puzzle.
possible function: returns true or false for a given number and location
solve: a recursion that fills the grid.
However I have a bug, how can I debug it without being trapped in an endless loop.
Is there some sort of force exit? Can you spot the bug?
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 possible(x, y, n) {
for (let i = 0; i < 9; i++) {
if (grid[y][i] === n) {
return false
}
}
for (let i = 0; i < 9; i++) {
if (grid[i][x] === n) {
return false
}
}
let x0 = Math.floor(x / 3) * 3;
let y0 = Math.floor(y / 3) * 3;
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (grid[y0 + i][x0 + j] === n) {
return false
}
}
}
return true;
}
function solve() {
for (let y = 0; y < 9; y++) {
for (let x = 0; x < 9; x++) {
if (grid[y][x] === 0) {
for (let n = 1; n < 10; n++) {
if(possible(y,x,n)){
grid[y][x] = n;
solve();
grid[y][x] = 0;
}
}
return;
}
}
}
}
solve();