Skip to lesson

N-Queens and Sudoku

N-Queens and Sudoku are the two flagship constraint-satisfaction puzzles of computer science. Both look intimidating on a 2D board, yet both collapse into clean, compact backtracking once you choose the right decision unit (one queen per row; one empty cell per step) and track row, column, and diagonal/box constraints in O(1) time.

Safe placement checks

In the N-Queens puzzle, you must place N chess queens on an N × N chessboard so that no two queens attack each other. A queen attacks every square in the same row, same column, and along both diagonals.

If you tried choosing any of the N² squares for each queen, there would be C(N², N) possibilities (over 4.4 billion for N = 8). Instead, notice that every row must contain at most one queen—and since we have N queens and N rows, every row must contain exactly one queen! That means recursion level r simply decides which column c (0 .. N - 1) gets the queen in row r. Because rows 0 .. r - 1 are already filled and rows r + 1 .. N - 1 are still empty, a scan-based isSafe(board, r, c) only needs to look upward:

  • Same column above: scan i from 0 to r - 1 at (i, c).
  • Upper-left diagonal (\): step (r - 1, c - 1), (r - 2, c - 2), ... while inside the board.
  • Upper-right diagonal (/): step (r - 1, c + 1), (r - 2, c + 2), ... while inside the board.

Sets for columns and diagonals

Scanning upward in isSafe takes O(N) time per candidate square. We can drop that to O(1) time with a simple coordinate invariant.

Example 1 · Brute force: try every placement of n queens (about C(n², n) boards)

QueensEveryPlacement.javaJava
public class QueensEveryPlacement {    static int n = 6;    static int placements = 0;    static int solutions = 0;    static int[] square = new int[n];
    static void choose(int from, int count) {        if (count == n) {            placements++;            if (noneAttack()) solutions++;            return;        }        for (int s = from; s < n * n; s++) {            square[count] = s;            choose(s + 1, count + 1);        }    }
    static boolean noneAttack() {        for (int a = 0; a < n; a++) {            for (int b = a + 1; b < n; b++) {                int r1 = square[a] / n, c1 = square[a] % n;                int r2 = square[b] / n, c2 = square[b] % n;                if (r1 == r2 || c1 == c2 || Math.abs(r1 - r2) == Math.abs(c1 - c2)) return false;            }        }        return true;    }
    public static void main(String[] args) {        choose(0, 0);        System.out.println("Placements checked: " + placements);        System.out.println("Solutions: " + solutions);    }}
Output
Placements checked: 1947792
Solutions: 4

What this code does

  • On a 6 × 6 board it checks all 1,947,792 ways to choose 6 squares out of 36, and finds the 4 solutions.
  • It is slow because it lets queens share a row and tests only after all six are placed.

Example 2 · Better: one queen per row, scan upward to check (O(n) per check)

NQueensIsSafeDemo.javaJava
import java.util.Arrays;
public class NQueensIsSafeDemo {    // O(N) upward scan check    public static boolean isSafeScan(char[][] board, int r, int c) {        int n = board.length;        // 1. Check same column above        for (int i = 0; i < r; i++) {            if (board[i][c] == 'Q') return false;        }        // 2. Check upper-left diagonal (r - 1, c - 1)...        for (int i = r - 1, j = c - 1; i >= 0 && j >= 0; i--, j--) {            if (board[i][j] == 'Q') return false;        }        // 3. Check upper-right diagonal (r - 1, c + 1)...        for (int i = r - 1, j = c + 1; i >= 0 && j < n; i--, j++) {            if (board[i][j] == 'Q') return false;        }        return true;    }
    public static int countQueens(int n, int r, char[][] board) {        if (r == n) return 1;        int total = 0;        for (int c = 0; c < n; c++) {            if (isSafeScan(board, r, c)) {                board[r][c] = 'Q';                total += countQueens(n, r + 1, board);                board[r][c] = '.';            }        }        return total;    }
    public static void main(String[] args) {        for (int n = 1; n <= 6; n++) {            char[][] board = new char[n][n];            for (char[] row : board) Arrays.fill(row, '.');            System.out.println("N = " + n + " -> " + countQueens(n, 0, board) + " solutions");        }    }}
Output
N = 1 -> 1 solutions
N = 2 -> 0 solutions
N = 3 -> 0 solutions
N = 4 -> 2 solutions
N = 5 -> 10 solutions
N = 6 -> 4 solutions

What this code does

  • Notice that isSafeScan never checks rows >= r or the same row r, because our row-by-row recursion guarantees that rows >= r are empty and row r has no queen yet.
  • For N = 2 and N = 3, there are 0 valid ways to place non-attacking queens.
  • One queen per row cuts the 1,947,792 boards to at most 6⁶ = 46,656, and a conflict rejects a row immediately, so it is much faster than the brute force above.
  • Each check still scans the column and both diagonals, which costs O(n).

Example 3 · Optimal: flag arrays make each check O(1) (O(n) extra space)

NQueensSolver.javaJava
import java.util.ArrayList;import java.util.Arrays;import java.util.List;
public class NQueensSolver {    public static List<List<String>> solveNQueens(int n) {        List<List<String>> results = new ArrayList<>();        char[][] board = new char[n][n];        for (char[] row : board) Arrays.fill(row, '.');
        boolean[] cols = new boolean[n];        boolean[] diag1 = new boolean[2 * n - 1]; // r - c + (n - 1)        boolean[] diag2 = new boolean[2 * n - 1]; // r + c
        backtrack(0, n, board, cols, diag1, diag2, results);        return results;    }
    private static void backtrack(int r, int n, char[][] board,                                  boolean[] cols, boolean[] diag1, boolean[] diag2,                                  List<List<String>> results) {        if (r == n) {            List<String> snapshot = new ArrayList<>(n);            for (char[] row : board) snapshot.add(new String(row));            results.add(snapshot);            return;        }        for (int c = 0; c < n; c++) {            int d1 = r - c + n - 1;            int d2 = r + c;            if (cols[c] || diag1[d1] || diag2[d2]) continue;
            board[r][c] = 'Q'; // 1. Choose            cols[c] = diag1[d1] = diag2[d2] = true;
            backtrack(r + 1, n, board, cols, diag1, diag2, results); // 2. Explore
            board[r][c] = '.'; // 3. Un-choose            cols[c] = diag1[d1] = diag2[d2] = false;        }    }
    public static void main(String[] args) {        List<List<String>> solutions4 = solveNQueens(4);        System.out.println("4-Queens solutions count: " + solutions4.size());        for (List<String> sol : solutions4) {            System.out.println(sol);        }        System.out.println("8-Queens solutions count: " + solveNQueens(8).size());    }}
Output
4-Queens solutions count: 2
[.Q.., ...Q, Q..., ..Q.]
[..Q., Q..., ...Q, .Q..]
8-Queens solutions count: 92

What this code does

  • Placing exactly one queen per row reduces the search space from C(64, 8) to at most 8⁸, and the column/diagonal arrays prune that further to just 92 valid boards for N = 8.
  • d1 = r - c + n - 1 shifts the difference r - c (which ranges from -(n - 1) to +(n - 1)) into 0 .. 2n - 2 so it can index diag1 directly.
  • Each check is now three array reads instead of a column scan and two diagonal scans, so the same search does less work on every square.

In detail:

  • Along any main diagonal (\, top-left to bottom-right), r and c both increase by 1 at each step, so the difference r - c is constant (shifted by + (N - 1) to stay in 0 .. 2N - 2 when indexing an array).
  • Along any anti-diagonal (/, bottom-left to top-right), r increases by 1 while c decreases by 1, so the sum r + c is constant (in the range 0 .. 2N - 2). By keeping three boolean[] arrays (or HashSet<Integer> sets)—colUsed[c], diag1Used[r - c + n - 1], and diag2Used[r + c]—checking whether (r, c) is under attack takes three O(1) array lookups!
In an interview, always mention the r - c and r + c diagonal invariants. Using boolean[] arrays instead of HashSet<Integer> avoids autoboxing and runs several times faster.

A Sudoku solver

In a 9 × 9 Sudoku, some cells are pre-filled with digits '1'–'9' and empty cells hold '.'. Every row, every column, and every 3 × 3 sub-box must contain the digits '1' through '9' without repetition.

Example 4 · Complete 9x9 Sudoku Solver with O(1) Row, Column, and Box Tracking

SudokuSolverDemo.javaJava
public class SudokuSolverDemo {    public static void solveSudoku(char[][] board) {        boolean[][] rowUsed = new boolean[9][10];        boolean[][] colUsed = new boolean[9][10];        boolean[][] boxUsed = new boolean[9][10];
        for (int r = 0; r < 9; r++) {            for (int c = 0; c < 9; c++) {                if (board[r][c] != '.') {                    int d = board[r][c] - '0';                    int box = (r / 3) * 3 + (c / 3);                    rowUsed[r][d] = colUsed[c][d] = boxUsed[box][d] = true;                }            }        }        backtrack(board, 0, rowUsed, colUsed, boxUsed);    }
    private static boolean backtrack(char[][] board, int pos,                                     boolean[][] rowUsed, boolean[][] colUsed, boolean[][] boxUsed) {        if (pos == 81) {            return true; // All 81 cells filled!        }        int r = pos / 9;        int c = pos % 9;        if (board[r][c] != '.') {            return backtrack(board, pos + 1, rowUsed, colUsed, boxUsed);        }
        int box = (r / 3) * 3 + (c / 3);        for (int d = 1; d <= 9; d++) {            if (rowUsed[r][d] || colUsed[c][d] || boxUsed[box][d]) continue;
            board[r][c] = (char) ('0' + d); // 1. Choose            rowUsed[r][d] = colUsed[c][d] = boxUsed[box][d] = true;
            if (backtrack(board, pos + 1, rowUsed, colUsed, boxUsed)) {                return true; // 2. Explore -> keep solution on board!            }
            board[r][c] = '.'; // 3. Un-choose on dead end            rowUsed[r][d] = colUsed[c][d] = boxUsed[box][d] = false;        }        return false;    }
    public static void main(String[] args) {        char[][] board = {            {'5','3','.','.','7','.','.','.','.'},            {'6','.','.','1','9','5','.','.','.'},            {'.','9','8','.','.','.','.','6','.'},            {'8','.','.','.','6','.','.','.','3'},            {'4','.','.','8','.','3','.','.','1'},            {'7','.','.','.','2','.','.','.','6'},            {'.','6','.','.','.','.','2','8','.'},            {'.','.','.','4','1','9','.','.','5'},            {'.','.','.','.','8','.','.','7','9'}        };        solveSudoku(board);        for (char[] row : board) {            System.out.println(new String(row));        }    }}
Output
534678912
672195348
198342567
859761423
426853791
713924856
961537284
287419635
345286179

What this code does

  • rowUsed[r][d], colUsed[c][d], and boxUsed[box][d] let us check whether digit d (1..9) is legal at (r, c) in O(1) time.
  • Notice that when backtrack(board, pos + 1, ...) returns true, we return true without resetting board[r][c] = '.'—because the caller wants the solved board left in place!

Which 3 × 3 box (numbered 0 .. 8) does cell (r, c) belong to? Row r is in box-row r / 3 (0, 1, 2) and column c is in box-col c / 3 (0, 1, 2), so *`boxIndex = (r / 3) 3 + (c / 3)**! To solve the board, advance cell by cell (pos = 0 .. 80, where r = pos / 9 and c = pos % 9). If board[r][c] != '.', skip straight to pos + 1. Otherwise, try digits d = '1' .. '9': if d is not yet used in row r, column c, or box boxIndex, place d (Choose), recurse on pos + 1 (Explore), and if that call returns true, **immediately return true**! Only if pos + 1 returns false do we reset board[r][c] = '.'` (Un-choose) and try the next digit.

Next step

Check your understanding

10 quick questions