Algorithms: Backtracking

Algorithms: Backtracking

Explore algorithms: backtracking code snippets and tutorials

Algorithms: Backtracking

Sudoku Backtracking Solver in C#

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

csharp
  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
using System;
// 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# / .NET 10: ReadOnlySpan<int> inputs, Span<int> outputs, primitive workspace arrays,
// Array.BinarySearch for LIS, and checked integer arithmetic. Invalid arguments and overflow
// throw exceptions.
//
// 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: Use Program.cs in a net10.0 console project; dotnet run.
// Tests for this exact source artifact run before publication. The accompanying source
// archive includes unit cases, runtime results, and source hashes.

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

    static int sudoku_solve(Span<int> board) {
        checked {
            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 = (((r / 3) * 3) + (c / 3));
                digit = board[cell];
                if ((digit == 0)) {
                    empty[count] = cell;
                    count = (count + 1);
                } else {
                    if (((rows[((r * 10) + digit)] != 0) || (cols[((c * 10) + digit)] != 0) || (boxes[((box * 10) + digit)] != 0))) {
                        return (-1);
                    }
                    rows[((r * 10) + digit)] = 1;
                    cols[((c * 10) + digit)] = 1;
                    boxes[((box * 10) + digit)] = 1;
                }
                cell = (cell + 1);
            }
            while (((position >= 0) && (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 = (digit + 1);
                while (((digit <= 9) && ((rows[((r * 10) + digit)] != 0) || (cols[((c * 10) + digit)] != 0) || (boxes[((box * 10) + digit)] != 0)))) {
                    digit = (digit + 1);
                }
                if ((digit == 10)) {
                    board[cell] = 0;
                    position = (position - 1);
                } else {
                    board[cell] = digit;
                    rows[((r * 10) + digit)] = 1;
                    cols[((c * 10) + digit)] = 1;
                    boxes[((box * 10) + digit)] = 1;
                    position = (position + 1);
                }
            }
            if ((position == count)) {
                return 1;
            }
            return 0;
        }
    }

    static void Main() {
        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);
        Console.WriteLine(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.WriteLine("[" + string.Join(", ", board) + "]");
    }
}
Algorithms: Backtracking

Sudoku Backtracking Solver in PHP

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

php
  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
<?php
declare(strict_types=1);
// Sudoku Backtracking Solver in PHP
//
// 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
// PHP 8.1+ on a 64-bit runtime: packed arrays, strict scalar types, read-only inputs by
// value using copy-on-write, references only for outputs, and checked 32-bit arithmetic.
// Invalid input and overflow throw exceptions. PHP arrays have higher overhead than native
// packed buffers in C/Java.
//
// 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: php example.php
// Tests for this exact source artifact run before publication. The accompanying source
// archive includes unit cases, runtime results, and source hashes.

function alg_require(bool $valid): void { if (!$valid) throw new InvalidArgumentException("invalid algorithm input"); }
function alg_checked(int|float $v): int { if ($v < -2147483648 || $v > 2147483647 || floor($v) != $v) throw new OverflowException("32-bit result overflow"); return (int)$v; }
function alg_add(int $a,int $b): int { return alg_checked($a+$b); }
function alg_sub(int $a,int $b): int { return alg_checked($a-$b); }
function alg_mul(int $a,int $b): int { return alg_checked($a*$b); }
function alg_size(int $n): int { alg_require($n>=0 && $n<=4000000); return $n; }

function sudoku_solve(array &$board): int {
    alg_require(array_is_list($board));
    alg_require((count($board) == 81));
    for ($alg_i = 0; $alg_i < count($board); $alg_i++) {
        $alg_value = $board[$alg_i];
        alg_require((($alg_value >= 0) && ($alg_value <= 9)));
    }
    $rows = array_fill(0, alg_size(90), 0);
    $cols = array_fill(0, alg_size(90), 0);
    $boxes = array_fill(0, alg_size(90), 0);
    $empty = array_fill(0, alg_size(81), 0);
    $count = 0;
    $position = 0;
    $cell = 0;
    $r = 0;
    $c = 0;
    $box = 0;
    $digit = 0;
    while (($cell < 81)) {
        $r = intdiv($cell, 9);
        $c = ($cell % 9);
        $box = alg_add(alg_mul(intdiv($r, 3), 3), intdiv($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 = intdiv($cell, 9);
        $c = ($cell % 9);
        $box = alg_add(alg_mul(intdiv($r, 3), 3), intdiv($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;
}

$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);
echo $result, PHP_EOL;
// 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]
echo json_encode($board), PHP_EOL;
Algorithms: Backtracking

N Queens Backtracking in Java

N-queens places one queen in each row with no shared columns or diagonals..

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
// N Queens Backtracking in Java
//
// PURPOSE
// N-queens places one queen in each row with no shared columns or diagonals.
//
// METHOD
// Try columns row by row. Keep occupied-column and diagonal marker arrays for constant-time
// safety checks. Backtrack when no column remains and count complete placements.
//
// COMPLEXITY
// Exponential search, bounded by O(n!) candidate placements with additional column-scan
// overhead; O(n) auxiliary space.
//
// CONTRACT
// 0<=n<=12. Returns solution count. The empty board has one placement. This implementation
// avoids recursion.
// 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.
// 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 n_queens(int n) {
        alg_require(((n >= 0) && (n <= 1000000)));
        alg_require(((n >= 0) && (n <= 12)));
        int[] columns = new int[alg_size(Math.addExact(n, 1))];
        int[] rising = new int[alg_size(Math.addExact(Math.multiplyExact(2, n), 1))];
        int[] falling = new int[alg_size(Math.addExact(Math.multiplyExact(2, n), 1))];
        int[] placement = new int[alg_size(Math.addExact(n, 1))];
        int row = 0;
        int col = 0;
        int count = 0;
        if ((n == 0)) {
            return 1;
        }
        while ((row >= 0)) {
            col = placement[row];
            if ((col > 0)) {
                columns[Math.subtractExact(col, 1)] = 0;
                rising[Math.subtractExact(Math.addExact(row, col), 1)] = 0;
                falling[Math.addExact(Math.subtractExact(row, col), n)] = 0;
            }
            while (((col < n) && ((columns[col] != 0) || (rising[Math.addExact(row, col)] != 0) || (falling[Math.subtractExact(Math.addExact(Math.subtractExact(row, col), n), 1)] != 0)))) {
                col = Math.addExact(col, 1);
            }
            if ((col == n)) {
                placement[row] = 0;
                row = Math.subtractExact(row, 1);
            } else {
                placement[row] = Math.addExact(col, 1);
                columns[col] = 1;
                rising[Math.addExact(row, col)] = 1;
                falling[Math.subtractExact(Math.addExact(Math.subtractExact(row, col), n), 1)] = 1;
                if ((row == Math.subtractExact(n, 1))) {
                    count = Math.addExact(count, 1);
                } else {
                    row = Math.addExact(row, 1);
                    placement[row] = 0;
                }
            }
        }
        return count;
    }

    public static void main(String[] args) {
        int n = 0;
        int result = n_queens(n);
        System.out.println(result);
    }
}
Algorithms: Backtracking

N Queens Backtracking in JavaScript

N-queens places one queen in each row with no shared columns or diagonals..

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
"use strict";
// N Queens Backtracking in JavaScript
//
// PURPOSE
// N-queens places one queen in each row with no shared columns or diagonals.
//
// METHOD
// Try columns row by row. Keep occupied-column and diagonal marker arrays for constant-time
// safety checks. Backtrack when no column remains and count complete placements.
//
// COMPLEXITY
// Exponential search, bounded by O(n!) candidate placements with additional column-scan
// overhead; O(n) auxiliary space.
//
// CONTRACT
// 0<=n<=12. Returns solution count. The empty board has one placement. This implementation
// avoids recursion.
// 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.
// 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 n_queens(n) {
    alg_require(Number.isInteger(n) && n >= -2147483648 && n <= 2147483647);
    alg_require(((n >= 0) && (n <= 1000000)));
    alg_require(((n >= 0) && (n <= 12)));
    let columns = new Int32Array(alg_size(alg_add(n, 1)));
    let rising = new Int32Array(alg_size(alg_add(alg_mul(2, n), 1)));
    let falling = new Int32Array(alg_size(alg_add(alg_mul(2, n), 1)));
    let placement = new Int32Array(alg_size(alg_add(n, 1)));
    let row = 0;
    let col = 0;
    let count = 0;
    if ((n == 0)) {
        return 1;
    }
    while ((row >= 0)) {
        col = placement[row];
        if ((col > 0)) {
            columns[alg_sub(col, 1)] = 0;
            rising[alg_sub(alg_add(row, col), 1)] = 0;
            falling[alg_add(alg_sub(row, col), n)] = 0;
        }
        while (((col < n) && ((columns[col] != 0) || (rising[alg_add(row, col)] != 0) || (falling[alg_sub(alg_add(alg_sub(row, col), n), 1)] != 0)))) {
            col = alg_add(col, 1);
        }
        if ((col == n)) {
            placement[row] = 0;
            row = alg_sub(row, 1);
        } else {
            placement[row] = alg_add(col, 1);
            columns[col] = 1;
            rising[alg_add(row, col)] = 1;
            falling[alg_sub(alg_add(alg_sub(row, col), n), 1)] = 1;
            if ((row == alg_sub(n, 1))) {
                count = alg_add(count, 1);
            } else {
                row = alg_add(row, 1);
                placement[row] = 0;
            }
        }
    }
    return count;
}

let n = 0;
let result = n_queens(n);
console.log(result);
Algorithms: Backtracking

N Queens Backtracking in Python

N-queens places one queen in each row with no shared columns or diagonals..

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

# N Queens Backtracking in Python
#
# PURPOSE
# N-queens places one queen in each row with no shared columns or diagonals.
#
# METHOD
# Try columns row by row. Keep occupied-column and diagonal marker arrays for constant-time
# safety checks. Backtrack when no column remains and count complete placements.
#
# COMPLEXITY
# Exponential search, bounded by O(n!) candidate placements with additional column-scan
# overhead; O(n) auxiliary space.
#
# CONTRACT
# 0<=n<=12. Returns solution count. The empty board has one placement. This implementation
# avoids recursion.
# 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.
# 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 n_queens(n: int) -> int:
    alg_require(type(n) is int and -2147483648 <= n <= 2147483647)
    alg_require(n >= 0 and n <= 1000000)
    alg_require(n >= 0 and n <= 12)
    columns: list[int] = [0] * alg_size(n + 1)
    rising: list[int] = [0] * alg_size(2 * n + 1)
    falling: list[int] = [0] * alg_size(2 * n + 1)
    placement: list[int] = [0] * alg_size(n + 1)
    row: int = 0
    col: int = 0
    count: int = 0
    if n == 0:
        return 1
    while row >= 0:
        col = placement[row]
        if col > 0:
            columns[col - 1] = 0
            rising[row + col - 1] = 0
            falling[row - col + n] = 0
        while col < n and (columns[col] != 0 or rising[row + col] != 0 or falling[row - col + n - 1] != 0):
            col += 1
        if col == n:
            placement[row] = 0
            row -= 1
        else:
            placement[row] = col + 1
            columns[col] = 1
            rising[row + col] = 1
            falling[row - col + n - 1] = 1
            if row == n - 1:
                count += 1
            else:
                row += 1
                placement[row] = 0
    return count

n = 0
result = n_queens(n)
print(result)