AlgoTales · Roadmap

Sudoku

Advanced · 12 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A sudoku solver fills empty cells with digits that do not repeat in the same row, column or box. When a cell has no legal digit, it undoes the last guess and tries another. It shows how to solve rule-heavy puzzles by guessing carefully and retreating.

Practical use cases

  • Web app: Puzzle app hint button. A newspaper puzzle website has a "Hint" button. When pressed, the solver fills in the grid from the current state, and the app reveals one correct cell. The same code also checks that a puzzle submitted by an editor has exactly one solution.
  • Web app: Timetable and exam slot builder. A school portal must give each class a subject in each period so no teacher is double-booked and no subject repeats badly in a day. It fills one slot at a time, and when a slot has no valid choice it undoes the previous one. The result is a clash-free timetable in seconds. Each new slot has only a few legal choices left after the earlier ones are placed, so the search stays small even for a school with 40 classes and 8 periods a day.
  • System: Constraint solvers. Software that builds airline crew rosters or allocates rooms uses this guess-check-undo cycle on thousands of rules, They add smarter tricks on top, such as filling the cell with the fewest options first, but the core stays guess, check and undo.

The story: The Newspaper Sudoku

Every morning Grandpa Bhaskar sat on the verandah with his tea and the newspaper's Sudoku. Mira, bored, asked for a smaller one, so Grandpa drew a 4×4 grid: put 1, 2, 3, 4 in each row, each column and each 2×2 box, with no repeats.

Mira found the first blank and thought: "Which digits are not already in this row, column and box?" She picked the smallest that fit and moved on to the next blank. It worked for a while, until she reached a blank where every digit clashed with something. She was stuck.

"Do not rub it all out," said Grandpa. "Go back to the last blank you filled, and try its next possible digit." Mira erased only that one square, tried another digit, and moved forward again. The puzzle slowly came out right, with the pencil used only where it was truly needed.

That is how a computer solves Sudoku: find an empty cell, try each digit that does not break a rule, go deeper, and if nothing fits, undo the last guess. Same choose, explore, un-choose, just on a grid.

How to spot this problem, and where you need it

You need to fill many slots with values, where each value has to obey rules relative to the others, and a wrong choice only shows up several steps later.

Signs you need it

  • The problem is a grid or table with some cells pre-filled and rules like "no repeats in a row, column or group".
  • You fill slots greedily and sometimes hit a dead end where nothing fits, so you must revisit an earlier choice.
  • The raw number of possible fillings is astronomical, yet most partial fillings can be rejected early.

Where to use it in a project

  • Timetable, exam seating or shift roster generators with no-clash rules.
  • Puzzle and game features such as validating a puzzle or revealing a hint.

The solution

Find the next empty cell. Try digits 1 to 9. For each digit, check the row, column and box for a repeat. If it is legal, write it in and move to the next empty cell. If none of the digits fit, you made a mistake earlier, so go back, erase the previous cell, and try its next digit. When no empty cells remain, you are done. Choosing the cell with the fewest legal digits first speeds this up further.

Payoff: Before: trillions of possible grids. After: a typical newspaper puzzle solves in a few milliseconds.

Explain it like I am 8

Fill each empty square with a number that is not already in its row, column or little box. If you reach a square where no number fits, you made a wrong guess earlier. Rub out only your last guess, try the next number, and carry on.

How it works, step by step

  1. Find the next empty cell (scan the grid). If there is none, the puzzle is solved.
  2. For each digit 1 to 4, check the three rules: not in the row, not in the column, not in the 2×2 box.
  3. Choose: write the digit in the cell, then explore by recursively solving the rest.
  4. If the recursion returns "solved", pass that success up and stop.
  5. Un-choose: otherwise clear the cell back to empty and try the next digit.
  6. If no digit works, return "not solvable" so the previous cell changes its guess.

The code in four languages

PHP

<?php
// Solve a 4x4 Sudoku (2x2 boxes). 0 means empty. Fills $g in place.
function canPlace(array $g, int $r, int $c, int $d): bool {
    for ($i = 0; $i < 4; $i++) {
        if ($g[$r][$i] === $d || $g[$i][$c] === $d) return false;   // row / column
    }
    $br = $r - $r % 2;
    $bc = $c - $c % 2;
    for ($i = 0; $i < 2; $i++) {
        for ($j = 0; $j < 2; $j++) {
            if ($g[$br + $i][$bc + $j] === $d) return false;        // 2x2 box
        }
    }
    return true;
}

function solve(array &$g): bool {
    for ($r = 0; $r < 4; $r++) {
        for ($c = 0; $c < 4; $c++) {
            if ($g[$r][$c] !== 0) continue;
            for ($d = 1; $d <= 4; $d++) {
                if (!canPlace($g, $r, $c, $d)) continue;
                $g[$r][$c] = $d;                  // choose
                if (solve($g)) return true;       // explore
                $g[$r][$c] = 0;                   // un-choose
            }
            return false;                         // no digit fits here
        }
    }
    return true;                                  // no empty cell left
}

$grid = [[1, 0, 0, 4], [0, 4, 1, 0], [2, 0, 4, 0], [0, 3, 0, 1]];
if (solve($grid)) {
    foreach ($grid as $row) echo implode(' ', $row) . "\n";
} else {
    echo "No solution\n";
}

JavaScript

// Solve a 4x4 Sudoku (2x2 boxes). 0 means empty. Fills g in place.
function canPlace(g, r, c, d) {
  for (let i = 0; i < 4; i++) {
    if (g[r][i] === d || g[i][c] === d) return false;     // row / column
  }
  const br = r - (r % 2), bc = c - (c % 2);
  for (let i = 0; i < 2; i++) {
    for (let j = 0; j < 2; j++) {
      if (g[br + i][bc + j] === d) return false;          // 2x2 box
    }
  }
  return true;
}

function solve(g) {
  for (let r = 0; r < 4; r++) {
    for (let c = 0; c < 4; c++) {
      if (g[r][c] !== 0) continue;
      for (let d = 1; d <= 4; d++) {
        if (!canPlace(g, r, c, d)) continue;
        g[r][c] = d;                          // choose
        if (solve(g)) return true;            // explore
        g[r][c] = 0;                          // un-choose
      }
      return false;                           // no digit fits here
    }
  }
  return true;                                // no empty cell left
}

const grid = [[1, 0, 0, 4], [0, 4, 1, 0], [2, 0, 4, 0], [0, 3, 0, 1]];
if (solve(grid)) {
  for (const row of grid) console.log(row.join(' '));
} else {
  console.log('No solution');
}

Java

import java.util.*;

public class Main {
    // Solve a 4x4 Sudoku (2x2 boxes). 0 means empty. Fills g in place.
    static boolean canPlace(int[][] g, int r, int c, int d) {
        for (int i = 0; i < 4; i++) {
            if (g[r][i] == d || g[i][c] == d) return false;     // row / column
        }
        int br = r - r % 2, bc = c - c % 2;
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++) {
                if (g[br + i][bc + j] == d) return false;       // 2x2 box
            }
        }
        return true;
    }

    static boolean solve(int[][] g) {
        for (int r = 0; r < 4; r++) {
            for (int c = 0; c < 4; c++) {
                if (g[r][c] != 0) continue;
                for (int d = 1; d <= 4; d++) {
                    if (!canPlace(g, r, c, d)) continue;
                    g[r][c] = d;                      // choose
                    if (solve(g)) return true;        // explore
                    g[r][c] = 0;                      // un-choose
                }
                return false;                         // no digit fits here
            }
        }
        return true;                                  // no empty cell left
    }

    public static void main(String[] args) {
        int[][] grid = {{1, 0, 0, 4}, {0, 4, 1, 0}, {2, 0, 4, 0}, {0, 3, 0, 1}};
        if (solve(grid)) {
            for (int[] row : grid) {
                StringJoiner sj = new StringJoiner(" ");
                for (int v : row) sj.add(String.valueOf(v));
                System.out.println(sj);
            }
        } else {
            System.out.println("No solution");
        }
    }
}

Go

package main

import "fmt"

// canPlace says whether digit d fits at row r, column c of a 4x4 Sudoku (2x2 boxes).
func canPlace(g [4][4]int, r, c, d int) bool {
	for i := 0; i < 4; i++ {
		if g[r][i] == d || g[i][c] == d { // row / column
			return false
		}
	}
	br, bc := r-r%2, c-c%2
	for i := 0; i < 2; i++ {
		for j := 0; j < 2; j++ {
			if g[br+i][bc+j] == d { // 2x2 box
				return false
			}
		}
	}
	return true
}

// solve fills g in place. 0 means empty.
func solve(g *[4][4]int) bool {
	for r := 0; r < 4; r++ {
		for c := 0; c < 4; c++ {
			if g[r][c] != 0 {
				continue
			}
			for d := 1; d <= 4; d++ {
				if !canPlace(*g, r, c, d) {
					continue
				}
				g[r][c] = d   // choose
				if solve(g) { // explore
					return true
				}
				g[r][c] = 0 // un-choose
			}
			return false // no digit fits here
		}
	}
	return true // no empty cell left
}

func main() {
	grid := [4][4]int{{1, 0, 0, 4}, {0, 4, 1, 0}, {2, 0, 4, 0}, {0, 3, 0, 1}}
	if solve(&grid) {
		for _, row := range grid {
			fmt.Println(row[0], row[1], row[2], row[3])
		}
	} else {
		fmt.Println("No solution")
	}
}

Time: O(9^m) · Extra space: O(m). Here m is the number of empty cells and 9 is the digits per cell (4 for our mini grid). In practice the rules prune most branches so real puzzles solve instantly.

Watch out for

  • Checking only the row and column and forgetting the box.
  • Not resetting the cell to 0 when a guess fails, so the next attempt thinks the cell is already filled.
  • Ignoring the return value of the recursive call. You must stop as soon as one branch succeeds.

Quick check

  1. What do we do when no digit fits in a cell?
    • Leave it blank and continue
    • Return failure so the earlier cell changes
    • Write 0 permanently
  2. How many checks does a digit pass before placing it (4×4)?
    • Row only
    • Row and column
    • Row, column and 2×2 box
    • Box only
  3. Why is the "solve" call placed inside an if?
    • To print the grid
    • To stop at the first solution and know if a guess succeeded
    • To count empty cells