Typorithm · hard

Sudoku Solver

▷ Interactive algorithm labsudoku-solverbacktrackingconstraintsgrid-fillchoose-explore-undo
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Sudoku Solver

0%

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.

Preparing algorithm lab…
01

Find an empty cell, try 1..9.

02

Validate row, column, and box.

03

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;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Find empty cell

Skip filled cells; only an empty '.' needs a digit.

if (board[r][c] !== ".") continue

2. Reject conflict

Skip a digit that clashes in its row, column, or 3x3 box.

if (!isValid(board, r, c, ch)) continue

3. Place digit

Write the candidate digit into the empty cell.

board[r][c] = ch

4. Explore

Recurse; a true result means the rest of the board was solved.

if (solve()) return true

5. Reset (undo)

Reset the cell so a different digit can be tried.

board[r][c] = "."

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Sudoku Solver: Visual Walkthrough & Practice · Typorithm | ApplyDjinn