我试图在Javascript中做一个Sudoku程序但是 我对Backtracking算法有一点问题,我在Java中使用“相同”代码并且工作正常,问题是(在调试之后)“k”是将成为matriz的新值的值,并且.. ...当k不能设置单元格返回堆栈(RECURSIVITY)但是当我应用Backtracking算法时k不是由k的最后一个值设置的。我在Safari,Chrome和Firefox中运行我的应用程序并给我相同的结果(100%肯定是我的代码)
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;
}