DEV Community

Arhan Khan
Arhan Khan

Posted on

Build a Sudoku Solver with JavaScript

A Sudoku solver is the project that makes recursion click. The puzzle is a 9x9 grid where every row, column, and 3x3 box must contain the digits 1–9 exactly once. The solver tries digits, backtracks when it hits a dead end, and finds the solution — and the algorithm is only about 30 lines.

The board is a 2D array with 0 for empty cells. The first function answers the only question the solver needs: is it legal to place this digit in this cell? Check the row, the column, and the 3x3 box:

function isValid(board, row, col, num) {
  for (let i = 0; i < 9; i++) {
    if (board[row][i] === num) return false;
    if (board[i][col] === num) return false;
  }
  const boxRow = Math.floor(row / 3) * 3;
  const boxCol = Math.floor(col / 3) * 3;
  for (let r = 0; r < 3; r++) {
    for (let c = 0; c < 3; c++) {
      if (board[boxRow + r][boxCol + c] === num) return false;
    }
  }
  return true;
}
Enter fullscreen mode Exit fullscreen mode

The solver itself is backtracking: find the first empty cell, try digits 1–9, and for each legal digit, place it and solve the rest of the board recursively. If a digit leads nowhere, remove it and try the next one. If no empty cell is left, the puzzle is solved:

function solve(board) {
  for (let row = 0; row < 9; row++) {
    for (let col = 0; col < 9; col++) {
      if (board[row][col] !== 0) continue;
      for (let num = 1; num <= 9; num++) {
        if (!isValid(board, row, col, num)) continue;
        board[row][col] = num;
        if (solve(board)) return true;
        board[row][col] = 0;
      }
      return false;
    }
  }
  return true;
}
Enter fullscreen mode Exit fullscreen mode

The user interface is a grid of 81 inputs. Rendering it from the board is a loop, and thicker borders every third row and column make the 3x3 boxes visible — a small CSS detail that makes the grid readable:

function render(board, givens) {
  const grid = document.getElementById("sudoku");
  grid.innerHTML = "";
  board.forEach((row, r) => {
    row.forEach((value, c) => {
      const input = document.createElement("input");
      input.type = "text";
      input.maxLength = 1;
      input.value = value || "";
      input.disabled = givens[r][c] !== 0;
      input.classList.toggle("given", givens[r][c] !== 0);
      if (c % 3 === 2 && c !== 8) input.classList.add("box-right");
      if (r % 3 === 2 && r !== 8) input.classList.add("box-bottom");
      input.addEventListener("input", (e) => {
        const n = parseInt(e.target.value, 10);
        board[r][c] = Number.isInteger(n) && n >= 1 && n <= 9 ? n : 0;
      });
      grid.appendChild(input);
    });
  });
}
Enter fullscreen mode Exit fullscreen mode

Two features make it a real tool rather than a demo. First, a "Solve" button that copies the board, runs the solver, and renders the result — showing which cells the solver filled in a different colour. Second, a validity check that tells the user immediately if their puzzle has a contradiction, instead of silently failing:

document.getElementById("solve-btn").addEventListener("click", () => {
  const copy = board.map((row) => [...row]);
  if (solve(copy)) {
    render(copy, givens);
    document.getElementById("message").textContent = "Solved!";
  } else {
    document.getElementById("message").textContent =
      "No solution exists — check the numbers you entered.";
  }
});
Enter fullscreen mode Exit fullscreen mode

Backtracking feels like magic the first time you see it work, but the logic is simple: try, recurse, undo. The same pattern solves mazes, the N-queens problem, and crossword fillers, so a Sudoku solver is one of the highest-value small projects a beginner can build. Ways to extend it: add a puzzle generator that removes digits from a solved board, add a hint button that fills one cell, add a timer, or animate the solving step by step so you can watch the backtracking happen.

Top comments (0)