Sudoku Solver
Backtracking O(9^m) O(m)Fills empty cells one at a time, trying digits 1–9 and backtracking whenever a digit breaks the rules.
Solving one preset puzzle — watch digits get tried, placed and undone.
1/94
Empty cell at (0, 1) — try to fill it.
InvariantEvery filled cell satisfies its row, column and box. A digit is only placed when it still holds.
sudoku.c
int valid(int g[9][9], int r, int c, int d) {for (int i = 0; i < 9; i++) {if (g[r][i] == d || g[i][c] == d)return 0;if (g[3*(r/3) + i/3][3*(c/3) + i%3] == d)return 0;}return 1;}int solve(int g[9][9]) {for (int r = 0; r < 9; r++) {for (int c = 0; c < 9; c++) {if (g[r][c]) continue;for (int d = 1; d <= 9; d++) {if (valid(g, r, c, d)) {g[r][c] = d;if (solve(g)) return 1;g[r][c] = 0; /* backtrack */}}return 0;}}return 1;}
How Sudoku Solver works
Find the next empty cell, try digits 1–9, recurse on the rest of the grid, and erase the digit when a dead end proves it wrong. Constraint checks keep the branching factor small.
When to use it
Constraint-satisfaction puzzles; the same skeleton solves scheduling and coloring instances.