Workshop › Sudoku › Step 19 of 28
The solver tries each option in the easiest cell and then solves the rest of the board with itself: a function that calls itself is recursive. When a guess leads nowhere, it undoes it and tries the next one: backtracking. It also counts how many solutions there are, up to a limit.
```js
// Backtracking: fill a cell with each digit that fits and try to solve the rest; undo when stuck.
// Counts solutions up to `limit`.
function countSolutions(board, limit = 2) {
const cell = bestCell(board)
if (!cell) return 1 // no empty cell left: solved
const { r, c, options } = cell
let count = 0
for (const d of options) {
board[r][c] = d
count += countSolutions(board, limit - count)
if (count >= limit) return count // keep the board as it is: that is the solution
board[r][c] = 0
}
return count
}
```limit of them, it stops and leaves the board filled in.board[r][c] = 0) before trying the next one.Under bestCell, write the comments and countSolutions.
Skills: Functions
← The easiest cell Random order →