I´m trying to do a Sudoku program in Javascript but I have a little problem with Backtracking algorithm, I have the "same" code in Java and works perfectly, the problem is (after debugging it) "k" is the value that is going to be the new value of matriz, and..... when a cell cannot be set by k return to the stack (RECURSIVITY) but when I apply Backtracking algorithm k is not set by the last value of k. I run my application in Safari, Chrome, and Firefox and give me the same result (100% sure is my code)
var matriz = [
[9, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]
];
function resolver(matriz)
{
for (i = 0; i <= 8; i++)
{
for (j = 0; j <= 8; j++)
{
if (matriz[i][j] != 0)
{
continue;
}
for (k = 1; k <= 9; k++)
{
if (insertar(matriz, i, j, k) == true)
{
matriz[i][j] = k;
b = resolver(matriz);
if (b == true)
{
return true;
}
matriz[i][j] = 0;
}
}
return false;
}
}
alert("SOLUCIÓN");
return true;
//SET CADA ELEMENTO DE LA MATRIZ;
}
function insertar(matriz, i, j, k)
{
for (a = 0; a <= 8; a++)
{
if (a != i && matriz[a][j] == k)
{
return false;
}
}
for (a = 0; a <= 8; a++)
{
if (a != j && matriz[i][a] == k)
{
return false;
}
}
y = Math.floor((i / 3)) * 3;
x = Math.floor((j / 3)) * 3;
for (a = 0; a < 3; a++)
{
for (b = 0; b < 3; b++)
{
if (a != i && b != j && matriz[y + a][x + b] == k)
{
return false;
}
}
}
return true;
}