Algo Visualizer

Recursion & Backtracking

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
7
9
Target Cell
Given Number
Debugger · v1.0
LIVE
1function solveSudoku(row, col) {
2 // 1: Base Case
3 if (row === 8 && col === 9) return true;
4
5 // 2: Check for next row
6 if (col === 9) { row++; col = 0; }
7
8 // 3: Skip filled cells
9 if (board[row][col] > 0) return solveSudoku(row, col + 1);
10
11 // 4: Try digits 1 to 9
12 for (let num = 1; num <= 9; num++) {
13 // 5: Is it safe?
14 if (isSafe(row, col, num)) {
15
16 // 6: Assign
17 board[row][col] = num;
18
19 // 7: Recur
20 if (solveSudoku(row, col + 1)) return true;
21 }
22 // 8: BACKTRACK
23 board[row][col] = 0;
24 }
25 // 9: No number worked
26 return false;
27}
1x
Recursion & Backtracking

Sudoku Solver

Step 1 of 5

A constraint satisfaction problem solved using a depth-first search through the space of possible digit placements.

The Three Golden Rules

A number (1-9) can only be placed if it is not already present in: 1) The current row, 2) The current column, 3) The 3×3 subgrid (box).

5
3
?
7
1
2
4
Testing valid digits for empty cell