N-Queens

Pattern: N-Queens

hard

Place one queen per row. For each row, try every column not attacked through its column or either diagonal, recurse into the next row, and undo. Three boolean arrays make each check O(1).

The problem

Place n queens on an n × n chessboard so that no two attack each other: no two share a row, a column or a diagonal. Return every such board, each as a list of strings with Q for a queen and . for an empty square. For example, n = 4 has two boards, .Q.. ...Q Q... ..Q. and ..Q. Q... ...Q .Q... n = 2 and n = 3 have none.

The function name solveNQueens matches LeetCode. Use the link above for the exact statement and limits. Any order of boards is accepted, so the tests sort them first. The GFG link covers the same puzzle.

Think first

  • How many queens can each row hold?
  • How can you tell in O(1) whether a square shares a diagonal with an earlier queen?
  • When you reach a row with no safe square, what do you do?

Hints

    Brute force, and why it fails

    Try every placement of n queens on n² squares: astronomically many. One queen per row cuts it to nⁿ, one per column too to n!, and diagonal checks during the search prune almost all of those.

    The key insight

    Every rule of the puzzle is a "line" (row, column, two diagonals), and each line has a simple number. Keeping one flag per line turns every attack check into three array lookups.

    Dry run

    Q . . .0 
    . . Q .1 
    . . . .2 
    . . . .3 

    n = 4. Row 0 tries column 0. Row 1 can use column 2 or 3. Try column 2.

    Step 1 of 4

    The plan

    function place(r):
        if r == n: record the board; return
        for c in 0..n-1:
            if col[c] or diag[r + c] or anti[r - c + n]: continue
            mark them; queen[r] = c
            place(r + 1)
            unmark them
    place(0)
    

    Complexity

    Time
    O(n!)
    Space
    O(n)

    At most n choices in the first row, n - 1 in the second and so on, and pruning cuts that far down. The arrays and the recursion are O(n), not counting the output.

    Edge cases

    • n = 1: one board, Q.
    • n = 2 and n = 3: no boards.
    • n = 8: 92 boards.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<List<String>> solveNQueens(int n) {
            List<List<String>> out = new ArrayList<>();
            place(0, n, new int[n], new boolean[n], new boolean[2 * n], new boolean[2 * n], out);
            return out;
        }
    
        private void place(int r, int n, int[] col, boolean[] usedCol, boolean[] diag, boolean[] anti, List<List<String>> out) {
            if (r == n) {                                   // a queen in every row: record the board
                List<String> board = new ArrayList<>();
                for (int i = 0; i < n; i++) {
                    char[] row = new char[n];
                    Arrays.fill(row, '.');
                    row[col[i]] = 'Q';
                    board.add(new String(row));
                }
                out.add(board);
                return;
            }
            for (int c = 0; c < n; c++) {
                if (usedCol[c] || diag[r + c] || anti[r - c + n]) continue;   // attacked: skip this square
                col[r] = c;
                usedCol[c] = diag[r + c] = anti[r - c + n] = true;
                place(r + 1, n, col, usedCol, diag, anti, out);
                usedCol[c] = diag[r + c] = anti[r - c + n] = false;           // undo before the next column
            }
        }
    }

    C++

    class Solution {
    public:
        vector<vector<string>> solveNQueens(int n) {
            vector<vector<string>> out;
            vector<int> col(n);
            vector<bool> usedCol(n, false), diag(2 * n, false), anti(2 * n, false);
            place(0, n, col, usedCol, diag, anti, out);
            return out;
        }
    
        void place(int r, int n, vector<int>& col, vector<bool>& usedCol, vector<bool>& diag, vector<bool>& anti,
                   vector<vector<string>>& out) {
            if (r == n) {                                   // a queen in every row: record the board
                vector<string> board(n, string(n, '.'));
                for (int i = 0; i < n; i++) board[i][col[i]] = 'Q';
                out.push_back(board);
                return;
            }
            for (int c = 0; c < n; c++) {
                if (usedCol[c] || diag[r + c] || anti[r - c + n]) continue;   // attacked: skip this square
                col[r] = c;
                usedCol[c] = diag[r + c] = anti[r - c + n] = true;
                place(r + 1, n, col, usedCol, diag, anti, out);
                usedCol[c] = diag[r + c] = anti[r - c + n] = false;           // undo before the next column
            }
        }
    };

    Python

    class Solution:
        def solveNQueens(self, n: int) -> list[list[str]]:
            out, col = [], [0] * n
            used_col, diag, anti = [False] * n, [False] * (2 * n), [False] * (2 * n)
    
            def place(r: int) -> None:
                if r == n:                          # a queen in every row: record the board
                    out.append(["." * c + "Q" + "." * (n - c - 1) for c in col])
                    return
                for c in range(n):
                    if used_col[c] or diag[r + c] or anti[r - c + n]:
                        continue                    # attacked: skip this square
                    col[r] = c
                    used_col[c] = diag[r + c] = anti[r - c + n] = True
                    place(r + 1)
                    used_col[c] = diag[r + c] = anti[r - c + n] = False   # undo before the next column
    
            place(0)
            return out

    Common mistakes

    • Using r - c as an index without adding n, which goes negative.
    • Forgetting to unmark, which blocks squares for later boards.
    • Building the board strings while still placing queens, instead of once at the end.

    Similar problems