Sudoku Backtracking Solver in C++

Algorithms: Backtracking November 15, 2026 C++

A Sudoku solver fills a 9 by 9 grid while respecting row, column, and box uniqueness..

cpp
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <stdexcept>
#include <cstdint>
#include <limits>
// Sudoku Backtracking Solver in C++
//
// PURPOSE
// A Sudoku solver fills a 9 by 9 grid while respecting row, column, and box uniqueness.
//
// METHOD
// Validate givens into three occupancy tables, collect empty cells, then try candidate
// digits with iterative backtracking. On exhaustion restore each original empty cell to
// zero.
//
// COMPLEXITY
// Exponential worst-case search in the number of empty cells; O(81) bounded workspace.
//
// CONTRACT
// board has 81 values in [0,9], where 0 means empty. Returns 1 after solving, 0 if
// unsatisfiable, -1 for conflicting givens. On failure leaves board unchanged.
// Public APIs infer array lengths except in C, which accepts pointer/length pairs. Vertex
// counts and matrix dimensions remain explicit. Arrays must contain signed 32-bit integers.
// Sorted order, correct tree topology, and caller-owned data-structure invariants are
// preconditions; checking them on every query would change query complexity.
// Scalar and shape checks are included. Value-range checks are included where needed to
// prevent invalid indexing or nontermination. Allocation sizes are capped at 4,000,000
// workspace entries. Arithmetic outside Python raises an error on 32-bit overflow; Python
// uses arbitrary precision. Native allocation failures propagate. In-place outputs may be
// partly updated after arithmetic failure. These are single-threaded, in-memory
// implementations.
//
// LANGUAGE DETAILS
// C++17: const vector references for inputs, mutable references for outputs, RAII workspace,
// standard lower_bound for LIS. Invalid inputs throw invalid_argument; overflow throws
// overflow_error; allocation failure propagates bad_alloc.
//
// EXAMPLE
// Expected return: 1.
// Expected board after call: [5, 3, 4, 6, 7, 8, 9, 1, 2, 6, 7, 2, 1, 9, 5, 3, 4, 8, 1, 9, 8,
// 3, 4, 2, 5, 6, 7, 8, 5, 9, 7, 6, 1, 4, 2, 3, 4, 2, 6, 8, 5, 3, 7, 9, 1, 7, 1, 3, 9, 2, 4,
// 8, 5, 6, 9, 6, 1, 5, 3, 7, 2, 8, 4, 2, 8, 7, 4, 1, 9, 6, 3, 5, 3, 4, 5, 2, 8, 6, 1, 7, 9].
// Run: g++ -std=c++17 -O2 example.cpp -o example && ./example
// Tests for this exact source artifact run before publication. The accompanying source
// archive includes unit cases, runtime results, and source hashes.

static int alg_min(int a, int b) { return a < b ? a : b; }
static int alg_max(int a, int b) { return a > b ? a : b; }
static void alg_require(bool valid) { if (!valid) throw std::invalid_argument("invalid algorithm input"); }
static int alg_checked(int64_t v) { if (v < INT32_MIN || v > INT32_MAX) throw std::overflow_error("32-bit result overflow"); return (int)v; }
static int alg_add(int a,int b) { return alg_checked((int64_t)a+b); }
static int alg_sub(int a,int b) { return alg_checked((int64_t)a-b); }
static int alg_mul(int a,int b) { return alg_checked((int64_t)a*b); }
static size_t alg_size(int n) { alg_require(n>=0 && n<=4000000); return (size_t)n; }

int sudoku_solve(std::vector<int>& board) {
    alg_require(board.size() <= 1000000);
    alg_require(((int)board.size() == 81));
    for (int alg_i = 0; alg_i < (int)board.size(); alg_i++) {
        int alg_value = board[alg_i];
        alg_require(((alg_value >= 0) && (alg_value <= 9)));
    }
    std::vector<int> rows(alg_size(90), 0);
    std::vector<int> cols(alg_size(90), 0);
    std::vector<int> boxes(alg_size(90), 0);
    std::vector<int> empty(alg_size(81), 0);
    int count = 0;
    int position = 0;
    int cell = 0;
    int r = 0;
    int c = 0;
    int box = 0;
    int digit = 0;
    while ((cell < 81)) {
        r = (cell / 9);
        c = (cell % 9);
        box = alg_add(alg_mul((r / 3), 3), (c / 3));
        digit = board[cell];
        if ((digit == 0)) {
            empty[count] = cell;
            count = alg_add(count, 1);
        } else {
            if (((rows[alg_add(alg_mul(r, 10), digit)] != 0) || (cols[alg_add(alg_mul(c, 10), digit)] != 0) || (boxes[alg_add(alg_mul(box, 10), digit)] != 0))) {
                return alg_sub(0, 1);
            }
            rows[alg_add(alg_mul(r, 10), digit)] = 1;
            cols[alg_add(alg_mul(c, 10), digit)] = 1;
            boxes[alg_add(alg_mul(box, 10), digit)] = 1;
        }
        cell = alg_add(cell, 1);
    }
    while (((position >= 0) && (position < count))) {
        cell = empty[position];
        r = (cell / 9);
        c = (cell % 9);
        box = alg_add(alg_mul((r / 3), 3), (c / 3));
        digit = board[cell];
        if ((digit != 0)) {
            rows[alg_add(alg_mul(r, 10), digit)] = 0;
            cols[alg_add(alg_mul(c, 10), digit)] = 0;
            boxes[alg_add(alg_mul(box, 10), digit)] = 0;
        }
        digit = alg_add(digit, 1);
        while (((digit <= 9) && ((rows[alg_add(alg_mul(r, 10), digit)] != 0) || (cols[alg_add(alg_mul(c, 10), digit)] != 0) || (boxes[alg_add(alg_mul(box, 10), digit)] != 0)))) {
            digit = alg_add(digit, 1);
        }
        if ((digit == 10)) {
            board[cell] = 0;
            position = alg_sub(position, 1);
        } else {
            board[cell] = digit;
            rows[alg_add(alg_mul(r, 10), digit)] = 1;
            cols[alg_add(alg_mul(c, 10), digit)] = 1;
            boxes[alg_add(alg_mul(box, 10), digit)] = 1;
            position = alg_add(position, 1);
        }
    }
    if ((position == count)) {
        return 1;
    }
    return 0;
}

int main(void) {
    std::vector<int> board = {5, 3, 4, 6, 7, 8, 9, 1, 2, 6, 7, 2, 1, 9, 5, 3, 4, 8, 1, 9, 8, 3, 4, 2, 5, 6, 7, 8, 5, 9, 7, 6, 1, 4, 2, 3, 4, 2, 6, 8, 5, 3, 7, 9, 1, 7, 1, 3, 9, 2, 4, 8, 5, 6, 9, 6, 1, 5, 3, 7, 2, 8, 4, 2, 8, 7, 4, 1, 9, 6, 3, 5, 3, 4, 5, 2, 8, 6, 1, 7, 0};
    int result = sudoku_solve(board);
    printf("%d\n", result);
    // Expected board: [5, 3, 4, 6, 7, 8, 9, 1, 2, 6, 7, 2, 1, 9, 5, 3, 4, 8, 1, 9, 8, 3, 4, 2, 5, 6, 7, 8, 5, 9, 7, 6, 1, 4, 2, 3, 4, 2, 6, 8, 5, 3, 7, 9, 1, 7, 1, 3, 9, 2, 4, 8, 5, 6, 9, 6, 1, 5, 3, 7, 2, 8, 4, 2, 8, 7, 4, 1, 9, 6, 3, 5, 3, 4, 5, 2, 8, 6, 1, 7, 9]
    for (int alg_print = 0; alg_print < 81; alg_print++) printf("%d ", board[alg_print]);
    printf("\n");
    return 0;
}