1. Find empty cell
Skip filled cells; only an empty '.' needs a digit.
if (board[r][c] !== ".") continueTyporithm · hard
Step 1 of 8 · intro card
Backtracking
Fill each empty cell by trying digits 1..9, keeping only ones valid in their row, column, and 3x3 box.
Scan for the first empty '.' cell, then try each digit from 1 to 9 in turn.
A digit is valid only if it does not already appear in the same row, column, or 3x3 box.
Place a valid digit and recurse; if the recursion fails, reset the cell and try the next digit.
Find an empty cell, try 1..9.
Validate row, column, and box.
Place, recurse, reset on failure.
function solveSudoku(board) {
function isValid(board, r, c, ch) {
for (let i = 0; i < 9; i += 1) {
if (board[r][i] === ch) return false;
if (board[i][c] === ch) return false;
const boxR = 3 * Math.floor(r / 3) + Math.floor(i / 3);
const boxC = 3 * Math.floor(c / 3) + (i % 3);
if (board[boxR][boxC] === ch) return false;
}
return true;
}
function solve() {
for (let r = 0; r < 9; r += 1) {
for (let c = 0; c < 9; c += 1) {
if (board[r][c] !== ".") continue;
for (let d = 1; d <= 9; d += 1) {
const ch = String(d);
if (!isValid(board, r, c, ch)) continue;
board[r][c] = ch;
if (solve()) return true;
board[r][c] = ".";
}
return false;
}
}
return true;
}
solve();
return board;
}Connect each part of the code to the concept before you type.
Skip filled cells; only an empty '.' needs a digit.
if (board[r][c] !== ".") continueSkip a digit that clashes in its row, column, or 3x3 box.
if (!isValid(board, r, c, ch)) continueWrite the candidate digit into the empty cell.
board[r][c] = chRecurse; a true result means the rest of the board was solved.
if (solve()) return trueReset the cell so a different digit can be tried.
board[r][c] = "."Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
Input9 × 9 Sudoku · small set of empty cells
Follow temporary values, local state and supporting structures at this step.
No temporary values have been saved in this frame yet.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state