Recursion & Backtracking · Pattern 2 of 9

N-Queens: place one queen per row

Every row holds exactly one queen, so place them row by row. Three boolean arrays for columns and both diagonals tell you in O(1) whether a square is safe.

1 variation · 1 problem · 1 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Place n pieces on an n × n board so none attack each other
  • Each row (or column) must hold exactly one item
  • You need every valid board, not just one

The template

2D Matrix
List<List<String>> solveNQueens(int n) {
    List<List<String>> out = new ArrayList<>();
    char[][] board = new char[n][n];
    for (char[] row : board) Arrays.fill(row, '.');
    place(0, board, new boolean[n], new boolean[2 * n], new boolean[2 * n], out);
    return out;
}
void place(int r, char[][] board, boolean[] col, boolean[] diag, boolean[] anti, List<List<String>> out) {
    int n = board.length;
    if (r == n) {                                     // every row has a queen
        List<String> b = new ArrayList<>();
        for (char[] row : board) b.add(new String(row));
        out.add(b);
        return;
    }
    for (int c = 0; c < n; c++) {
        if (col[c] || diag[r - c + n] || anti[r + c]) continue;   // attacked
        col[c] = diag[r - c + n] = anti[r + c] = true;
        board[r][c] = 'Q';
        place(r + 1, board, col, diag, anti, out);
        board[r][c] = '.';                            // undo
        col[c] = diag[r - c + n] = anti[r + c] = false;
    }
}

The variations

  1. 1One queen per row

    The row is the depth of the recursion and the column is the choice. A square is safe when its column, its r − c diagonal and its r + c anti-diagonal are all unused.

Mistakes to avoid

  • r - c can be negative: shift it by n before using it as an array index.
  • Scanning the whole board to check safety at every step: three arrays make the check O(1).
  • Undoing the board but not the column and diagonal markers (or the other way round).
Next: Pick / not-pick: subsets, combinations and sums →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.