Algorithms: Backtracking

Algorithms: Backtracking

Explore algorithms: backtracking code snippets and tutorials

Algorithms: Backtracking

Sudoku Backtracking Solver in Java

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

java
  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
// Sudoku Backtracking Solver in Java
//
// 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
// Java 17+: primitive int arrays, Arrays.binarySearch for LIS, and Math exact arithmetic.
// Invalid input throws IllegalArgumentException; arithmetic overflow throws
// ArithmeticException.
//
// 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: javac AlgorithmExample.java && java AlgorithmExample
// Tests for this exact source artifact run before publication. The accompanying source
// archive includes unit cases, runtime results, and source hashes.

class AlgorithmExample {
    static void alg_require(boolean valid) { if (!valid) throw new IllegalArgumentException("invalid algorithm input"); }
    static int alg_size(int n) { alg_require(n>=0 && n<=4000000); return n; }

    static int sudoku_solve(int[] board) {
        java.util.Objects.requireNonNull(board, "board");
        alg_require((board.length == 81));
        for (int alg_i = 0; alg_i < board.length; alg_i++) {
            int alg_value = board[alg_i];
            alg_require(((alg_value >= 0) && (alg_value <= 9)));
        }
        int[] rows = new int[alg_size(90)];
        int[] cols = new int[alg_size(90)];
        int[] boxes = new int[alg_size(90)];
        int[] empty = new int[alg_size(81)];
        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 = Math.addExact(Math.multiplyExact((r / 3), 3), (c / 3));
            digit = board[cell];
            if ((digit == 0)) {
                empty[count] = cell;
                count = Math.addExact(count, 1);
            } else {
                if (((rows[Math.addExact(Math.multiplyExact(r, 10), digit)] != 0) || (cols[Math.addExact(Math.multiplyExact(c, 10), digit)] != 0) || (boxes[Math.addExact(Math.multiplyExact(box, 10), digit)] != 0))) {
                    return Math.negateExact(1);
                }
                rows[Math.addExact(Math.multiplyExact(r, 10), digit)] = 1;
                cols[Math.addExact(Math.multiplyExact(c, 10), digit)] = 1;
                boxes[Math.addExact(Math.multiplyExact(box, 10), digit)] = 1;
            }
            cell = Math.addExact(cell, 1);
        }
        while (((position >= 0) && (position < count))) {
            cell = empty[position];
            r = (cell / 9);
            c = (cell % 9);
            box = Math.addExact(Math.multiplyExact((r / 3), 3), (c / 3));
            digit = board[cell];
            if ((digit != 0)) {
                rows[Math.addExact(Math.multiplyExact(r, 10), digit)] = 0;
                cols[Math.addExact(Math.multiplyExact(c, 10), digit)] = 0;
                boxes[Math.addExact(Math.multiplyExact(box, 10), digit)] = 0;
            }
            digit = Math.addExact(digit, 1);
            while (((digit <= 9) && ((rows[Math.addExact(Math.multiplyExact(r, 10), digit)] != 0) || (cols[Math.addExact(Math.multiplyExact(c, 10), digit)] != 0) || (boxes[Math.addExact(Math.multiplyExact(box, 10), digit)] != 0)))) {
                digit = Math.addExact(digit, 1);
            }
            if ((digit == 10)) {
                board[cell] = 0;
                position = Math.subtractExact(position, 1);
            } else {
                board[cell] = digit;
                rows[Math.addExact(Math.multiplyExact(r, 10), digit)] = 1;
                cols[Math.addExact(Math.multiplyExact(c, 10), digit)] = 1;
                boxes[Math.addExact(Math.multiplyExact(box, 10), digit)] = 1;
                position = Math.addExact(position, 1);
            }
        }
        if ((position == count)) {
            return 1;
        }
        return 0;
    }

    public static void main(String[] args) {
        int[] board = new int[] {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);
        System.out.println(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]
        System.out.println(java.util.Arrays.toString(board));
    }
}
Algorithms: Backtracking

Sudoku Backtracking Solver in JavaScript

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

javascript
  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
"use strict";
// Sudoku Backtracking Solver in JavaScript
//
// 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
// Node.js 18+: Int32Array inputs and workspaces provide compact integer storage. Automatic
// lengths and checked arithmetic reject values outside signed 32-bit. Invalid inputs or
// overflow throw RangeError.
//
// 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: node example.js
// Tests for this exact source artifact run before publication. The accompanying source
// archive includes unit cases, runtime results, and source hashes.

function alg_require(valid) { if (!valid) throw new RangeError("invalid algorithm input"); }
function alg_checked(v) { if (!Number.isInteger(v) || v < -2147483648 || v > 2147483647) throw new RangeError("32-bit result overflow"); return v; }
function alg_add(a,b) { return alg_checked(a+b); }
function alg_sub(a,b) { return alg_checked(a-b); }
function alg_mul(a,b) { return alg_checked(a*b); }
function alg_size(n) { alg_require(Number.isInteger(n) && n>=0 && n<=4000000); return n; }

function sudoku_solve(board) {
    alg_require(board instanceof Int32Array);
    alg_require((board.length == 81));
    for (let alg_i = 0; alg_i < board.length; alg_i++) {
        let alg_value = board[alg_i];
        alg_require(((alg_value >= 0) && (alg_value <= 9)));
    }
    let rows = new Int32Array(alg_size(90));
    let cols = new Int32Array(alg_size(90));
    let boxes = new Int32Array(alg_size(90));
    let empty = new Int32Array(alg_size(81));
    let count = 0;
    let position = 0;
    let cell = 0;
    let r = 0;
    let c = 0;
    let box = 0;
    let digit = 0;
    while ((cell < 81)) {
        r = Math.floor(cell / 9);
        c = (cell % 9);
        box = alg_add(alg_mul(Math.floor(r / 3), 3), Math.floor(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 = Math.floor(cell / 9);
        c = (cell % 9);
        box = alg_add(alg_mul(Math.floor(r / 3), 3), Math.floor(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;
}

let board = new Int32Array([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]);
let result = sudoku_solve(board);
console.log(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]
console.log(Array.from(board));
Algorithms: Backtracking

Sudoku Backtracking Solver in Python

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

python
  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
from bisect import bisect_left

# Sudoku Backtracking Solver in Python
#
# 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
# Python 3.9+: automatic lengths, native lists, arbitrary-precision arithmetic, and
# bisect_left for LIS. Invalid scalar/shape inputs raise ValueError. Integer element types
# and sorted/tree invariants remain caller preconditions.
#
# 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: python example.py
# Tests for this exact source artifact run before publication. The accompanying source
# archive includes unit cases, runtime results, and source hashes.

def alg_require(condition):
    if not condition:
        raise ValueError("invalid algorithm input; see contract")
def alg_size(n):
    alg_require(0 <= n <= 4000000)
    return n

def sudoku_solve(board: list[int]) -> int:
    alg_require(isinstance(board, list) and len(board) <= 1000000)
    alg_require(len(board) == 81)
    for value in board:
        alg_require(value >= 0 and value <= 9)
    rows: list[int] = [0] * alg_size(90)
    cols: list[int] = [0] * alg_size(90)
    boxes: list[int] = [0] * alg_size(90)
    empty: list[int] = [0] * alg_size(81)
    count: int = 0
    position: int = 0
    cell: int = 0
    r: int = 0
    c: int = 0
    box: int = 0
    digit: int = 0
    while cell < 81:
        r = cell // 9
        c = cell % 9
        box = r // 3 * 3 + c // 3
        digit = board[cell]
        if digit == 0:
            empty[count] = cell
            count += 1
        else:
            if rows[r * 10 + digit] != 0 or cols[c * 10 + digit] != 0 or boxes[box * 10 + digit] != 0:
                return -1
            rows[r * 10 + digit] = 1
            cols[c * 10 + digit] = 1
            boxes[box * 10 + digit] = 1
        cell += 1
    while position >= 0 and position < count:
        cell = empty[position]
        r = cell // 9
        c = cell % 9
        box = r // 3 * 3 + c // 3
        digit = board[cell]
        if digit != 0:
            rows[r * 10 + digit] = 0
            cols[c * 10 + digit] = 0
            boxes[box * 10 + digit] = 0
        digit += 1
        while digit <= 9 and (rows[r * 10 + digit] != 0 or cols[c * 10 + digit] != 0 or boxes[box * 10 + digit] != 0):
            digit += 1
        if digit == 10:
            board[cell] = 0
            position -= 1
        else:
            board[cell] = digit
            rows[r * 10 + digit] = 1
            cols[c * 10 + digit] = 1
            boxes[box * 10 + digit] = 1
            position += 1
    if position == count:
        return 1
    return 0

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]
result = sudoku_solve(board)
print(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]
print(board)
Algorithms: Backtracking

Sudoku Backtracking Solver in C

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

c
  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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <limits.h>
#include <errno.h>
// 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
// C99: checked calloc/free workspace, const input pointers, explicit size_t lengths. Errors
// return INT_MIN with errno=EINVAL, ERANGE, or ENOMEM. Check errno before using a result.
// Input/output arrays must not alias. No variable-length stack arrays.
//
// 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: gcc -std=c99 -O2 example.c -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 int alg_checked(int64_t v, int *error) {
    if (v < INT_MIN || v > INT_MAX) { *error = 1; return 0; }
    return (int)v;
}
static int alg_add(int a, int b, int *e) { return alg_checked((int64_t)a+b,e); }
static int alg_sub(int a, int b, int *e) { return alg_checked((int64_t)a-b,e); }
static int alg_mul(int a, int b, int *e) { return alg_checked((int64_t)a*b,e); }

int sudoku_solve(int *board, size_t board_length) {
    int alg_error = 0;
    int alg_result = INT_MIN;
    errno = 0;
    int *rows = NULL;
    int *cols = NULL;
    int *boxes = NULL;
    int *empty = NULL;
    if (board_length > 1000000 || (board_length && !board)) { errno = EINVAL; alg_result = INT_MIN; goto alg_cleanup; }
    if (!(((int)board_length == 81))) { errno = EINVAL; alg_result = INT_MIN; goto alg_cleanup; }
    if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
    for (int alg_i = 0; alg_i < (int)board_length; alg_i++) {
        int alg_value = board[alg_i];
        if (!(((alg_value >= 0) && (alg_value <= 9)))) { errno = EINVAL; alg_result = INT_MIN; goto alg_cleanup; }
        if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
    }
    {
        int alg_length = 90;
        if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
        if (alg_length < 0 || alg_length > 4000000) { errno = EINVAL; alg_result = INT_MIN; goto alg_cleanup; }
        rows = calloc((size_t)(alg_length ? alg_length : 1), sizeof(*rows));
        if (!rows) { errno = ENOMEM; alg_result = INT_MIN; goto alg_cleanup; }
    }
    {
        int alg_length = 90;
        if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
        if (alg_length < 0 || alg_length > 4000000) { errno = EINVAL; alg_result = INT_MIN; goto alg_cleanup; }
        cols = calloc((size_t)(alg_length ? alg_length : 1), sizeof(*cols));
        if (!cols) { errno = ENOMEM; alg_result = INT_MIN; goto alg_cleanup; }
    }
    {
        int alg_length = 90;
        if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
        if (alg_length < 0 || alg_length > 4000000) { errno = EINVAL; alg_result = INT_MIN; goto alg_cleanup; }
        boxes = calloc((size_t)(alg_length ? alg_length : 1), sizeof(*boxes));
        if (!boxes) { errno = ENOMEM; alg_result = INT_MIN; goto alg_cleanup; }
    }
    {
        int alg_length = 81;
        if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
        if (alg_length < 0 || alg_length > 4000000) { errno = EINVAL; alg_result = INT_MIN; goto alg_cleanup; }
        empty = calloc((size_t)(alg_length ? alg_length : 1), sizeof(*empty));
        if (!empty) { errno = ENOMEM; alg_result = INT_MIN; goto alg_cleanup; }
    }
    int count = 0;
    if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
    int position = 0;
    if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
    int cell = 0;
    if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
    int r = 0;
    if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
    int c = 0;
    if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
    int box = 0;
    if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
    int digit = 0;
    if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
    while (1) {
        int alg_condition = (cell < 81);
        if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
        if (!alg_condition) break;
        r = (cell / 9);
        if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
        c = (cell % 9);
        if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
        box = alg_add(alg_mul((r / 3), 3, &alg_error), (c / 3), &alg_error);
        if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
        digit = board[cell];
        if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
        int alg_condition_1 = (digit == 0);
        if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
        if (alg_condition_1) {
            empty[count] = cell;
            if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
            count = alg_add(count, 1, &alg_error);
            if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
        } else {
            int alg_condition_2 = ((rows[alg_add(alg_mul(r, 10, &alg_error), digit, &alg_error)] != 0) || (cols[alg_add(alg_mul(c, 10, &alg_error), digit, &alg_error)] != 0) || (boxes[alg_add(alg_mul(box, 10, &alg_error), digit, &alg_error)] != 0));
            if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
            if (alg_condition_2) {
                alg_result = alg_sub(0, 1, &alg_error);
                if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
                goto alg_cleanup;
            }
            rows[alg_add(alg_mul(r, 10, &alg_error), digit, &alg_error)] = 1;
            if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
            cols[alg_add(alg_mul(c, 10, &alg_error), digit, &alg_error)] = 1;
            if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
            boxes[alg_add(alg_mul(box, 10, &alg_error), digit, &alg_error)] = 1;
            if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
        }
        cell = alg_add(cell, 1, &alg_error);
        if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
    }
    while (1) {
        int alg_condition = ((position >= 0) && (position < count));
        if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
        if (!alg_condition) break;
        cell = empty[position];
        if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
        r = (cell / 9);
        if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
        c = (cell % 9);
        if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
        box = alg_add(alg_mul((r / 3), 3, &alg_error), (c / 3), &alg_error);
        if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
        digit = board[cell];
        if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
        int alg_condition_3 = (digit != 0);
        if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
        if (alg_condition_3) {
            rows[alg_add(alg_mul(r, 10, &alg_error), digit, &alg_error)] = 0;
            if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
            cols[alg_add(alg_mul(c, 10, &alg_error), digit, &alg_error)] = 0;
            if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
            boxes[alg_add(alg_mul(box, 10, &alg_error), digit, &alg_error)] = 0;
            if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
        }
        digit = alg_add(digit, 1, &alg_error);
        if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
        while (1) {
            int alg_condition = ((digit <= 9) && ((rows[alg_add(alg_mul(r, 10, &alg_error), digit, &alg_error)] != 0) || (cols[alg_add(alg_mul(c, 10, &alg_error), digit, &alg_error)] != 0) || (boxes[alg_add(alg_mul(box, 10, &alg_error), digit, &alg_error)] != 0)));
            if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
            if (!alg_condition) break;
            digit = alg_add(digit, 1, &alg_error);
            if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
        }
        int alg_condition_4 = (digit == 10);
        if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
        if (alg_condition_4) {
            board[cell] = 0;
            if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
            position = alg_sub(position, 1, &alg_error);
            if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
        } else {
            board[cell] = digit;
            if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
            rows[alg_add(alg_mul(r, 10, &alg_error), digit, &alg_error)] = 1;
            if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
            cols[alg_add(alg_mul(c, 10, &alg_error), digit, &alg_error)] = 1;
            if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
            boxes[alg_add(alg_mul(box, 10, &alg_error), digit, &alg_error)] = 1;
            if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
            position = alg_add(position, 1, &alg_error);
            if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
        }
    }
    int alg_condition_5 = (position == count);
    if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
    if (alg_condition_5) {
        alg_result = 1;
        if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
        goto alg_cleanup;
    }
    alg_result = 0;
    if (alg_error) { errno = ERANGE; alg_result = INT_MIN; goto alg_cleanup; }
    goto alg_cleanup;
alg_cleanup:
    free(rows);
    free(cols);
    free(boxes);
    free(empty);
    return alg_result;
}

int main(void) {
    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, 81);
    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");
    if (errno) { perror("algorithm"); return 1; }
    return 0;
}
Algorithms: Backtracking

Sudoku Backtracking Solver in 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;
}