let puzzle = [
[0, 0, 7, 0, 0, 3, 5, 0, 0],
[6, 0, 5, 4, 0, 8, 3, 0, 2],
[0, 0, 4, 5, 2, 0, 9, 0, 6],
[0, 0, 0, 0, 7, 1, 2, 0, 9],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[8, 0, 9, 2, 3, 0, 0, 0, 0],
[9, 0, 1, 0, 8, 5, 6, 0, 0],
[7, 0, 3, 9, 0, 2, 8, 0, 5],
[0, 0, 8, 7, 0, 0, 1, 0, 0]
];
class Sudoku
{
constructor(puzzle)
{
this.sudoku = puzzle;
}
isPossible(y, x, n)
{
for (let i = 0; i < 9; i++)
{
if (this.sudoku[y][i] == n)
return false;
}
for (let i = 0; i < 9; i++)
{
if (this.sudoku[i][x] == n)
return false;
}
let y0 = (Math.floor(y / 3) * 3);
let x0 = (Math.floor(x / 3) * 3);
for (let i = 0; i < 3; i++)
{
for (let j = 0; j < 3; j++)
{
if (this.sudoku[y0 + i][x0 + j] == n)
return false;
}
}
return true;
}
solve()
{
for (let y = 0; y < 9; y++)
{
for (let x = 0; x < 9; x++)
{
if (this.sudoku[y][x] == 0)
{
for (let n = 1; n <= 9; n++)
{
if (this.isPossible(y, x, n))
{
this.sudoku[y][x] = n;
this.solve();
this.sudoku[y][x] = 0;
}
}
return;
}
}
}
console.table(this.sudoku);
}
}
let s = new Sudoku(puzzle);
s.solve();
这本书写得很好.然而,调试表明,在console.table
之后,代码继续运行,并将矩阵恢复到其原始状态.但是,再也不会执行console.table
行.因此,在solve
方法之外,this.sudoku
只是原始的puzzle
矩阵.