Я написал JavaScript, чтобы решить головоломку судоку с возвратом. Моя цель - сохранить решение в переменной. Прямо сейчас я могу назвать решение только один раз.
var grid = [
[0,1],
[1,0]
]
function solve() {
/// ... the recursive function that change the value of the grid variable.
data = console.log(grid);
return data;
}
var result = solve();
console.log(result);
Мой ожидаемый результат для console.log(result)
- [[0,1], [1,0]]
, но вместо этого результат undefined
.
=== tl:dr
the sudoku solver in javascript
/// a string of digits, 1 - 9, and '.' as spaces. Each character represent a square, e.g.,
/// 5 3 . | . 7 . | . . .
/// 6 . . | 1 9 5 | . . .
/// . 9 8 | . . . | . 6 .
/// ------+-------+------
/// 8 . . | . 6 . | . . 3
/// 4 . . | 8 . 3 | . . 1
/// 7 . . | . 2 . | . . 6
/// ------+-------+------
/// . 6 . | . . . | 2 8 .
/// . . . | 4 1 9 | . . 5
/// . . . | . 8 . | . . .
var 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(r,c,n) {
/// check the row
for (let i=0;i<9;i++) if (grid[r][i] == n) return false;
/// check the column
for (let i=0;i<9;i++) if (grid[i][c] == n) return false;
/// check the 3x3 grid
let r0 = Math.floor(r/3)*3;
let c0 = Math.floor(c/3)*3;
for (let i=0;i<3;i++) {
for (let j=0;j<3;j++) {
if (grid[r0+i][c0+j] == n) return false;
}
}
/// all check passed
return true;
}
function solve() {
for (let r=0;r<9;r++) {
for (let c=0;c<9;c++) {
/// check grid with value of 0
if (grid[r][c] === 0) {
/// check for possible solution
for (let n=1;n<10;n++) {
if (possible(r,c,n)) {
/// there is a possibility of the selected solution is a bad one.
/// to solve this, use backtracking: try -> if it turns out the solution is a bad one, we go back to 0.
grid[r][c] = n;
/// recursion
solve();
grid[r][c] = 0;
}
}
/// if there is no solution, we have to return.
return;
}
}
}
data = console.log(grid);
return data;
}
var result = solve()
console.log(result)
изменить: использование JSON.stringify
и вызов функции solve()
выводит решение один раз, но результат по-прежнему не сохраняется в переменной.
...
data = console.log(JSON.stringify(grid));
return data;
}
var result = solve()
console.log(result)
console.log
всегда возвращаетundefined
, так что это то, что вы назначаете здесьdata = console.log(grid);
. Так что не делайте этого, а делайте прямоdata = grid
. Хотя вам может потребоваться сделать глубокий клонgrid
в какой-то момент, если вы постоянно его меняете. - person VLAZ   schedule 28.07.2020console.log(grid)
наdata = grid
и вызвалconsole.log(data)
вне функции. Результатом является исходная сеточная переменная, чего не ожидалось. - person kidfrom   schedule 28.07.2020