</>

51. N-Queens

Hard NeetCode 150
Backtracking Time O(N!) Space O(N)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Backtracking
Time
O(N!)
Space
O(N)

Standard Solution (C++)

SummaryPlace N non-attacking queens on an N×N chessboard such that no two queens share the same row, column, or diagonal, and return all distinct board configurations.

Approach
  • Place queens one row at a time via backtracking; since each row gets exactly one queen, the search space is at most N! placements.
  • Track three boolean sets: occupied columns, occupied "/" diagonals (row+col is constant), and occupied "" diagonals (row−col is constant). Each set is O(1) to query and update.
  • When a valid column is found in the current row, place the queen, recurse to the next row, then undo the placement (classic backtrack).
  • A complete placement (row == n) is snapshotted and added to the result.
#include <vector>
#include <string>
using namespace std;

class Solution {
public:
    vector<vector<string>> solveNQueens(int n) {
        vector<vector<string>> result;
        vector<string> board(n, string(n, '.'));

        // cols[c]        = column c is occupied
        // diag[r+c]      = "/" diagonal is occupied  (0 .. 2n-2)
        // anti[r-c+n-1]  = "\" diagonal is occupied  (0 .. 2n-2)
        vector<bool> cols(n, false), diag(2*n-1, false), anti(2*n-1, false);

        backtrack(board, result, cols, diag, anti, 0, n);
        return result;
    }

private:
    void backtrack(vector<string>& board,
                   vector<vector<string>>& result,
                   vector<bool>& cols,
                   vector<bool>& diag,   // row+col constant => "/" diagonal
                   vector<bool>& anti,   // row-col+n-1 constant => "\" diagonal
                   int row, int n) {
        if (row == n) {
            result.push_back(board);
            return;
        }
        for (int col = 0; col < n; ++col) {
            int d = row + col;
            int a = row - col + n - 1;
            if (cols[col] || diag[d] || anti[a]) continue;

            // place
            board[row][col] = 'Q';
            cols[col] = diag[d] = anti[a] = true;

            backtrack(board, result, cols, diag, anti, row + 1, n);

            // remove
            board[row][col] = '.';
            cols[col] = diag[d] = anti[a] = false;
        }
    }
};
Time O(N!) Space O(N)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class Solution {
public:

    void dfs(vector<string>& cur, int n, int curQNum){ // curQNum means current row
        if(curQNum==n){
            res.push_back(cur);
            return;
        }
        for(int col=0; col<n; ++col){
            if(!cols[col] && !diag1[curQNum+col] && !diag2[curQNum-col+n-1]){
                cur[curQNum][col]='Q';
                cols[col]=true;
                diag1[curQNum+col]=true;
                diag2[curQNum-col+n-1]=true;

                dfs(cur, n, curQNum+1);
                
                cols[col]=false;
                cur[curQNum][col]='.';
                diag1[curQNum+col]=false;
                diag2[curQNum-col+n-1]=false;
            }
        }
    }

    vector<vector<string>> solveNQueens(int n) {
        vector<string> cur(n, string(n, '.'));
        cols.assign(n, false);
        diag1.assign(2*n-1, false);
        diag2.assign(2*n-1, false);
        dfs(cur, n, 0);
        return res;
    }

    vector<vector<string>> res;
    vector<bool> cols;
    vector<bool> diag1; // 0~2n-2
    vector<bool> diag2; // -(n-1)~(n-1) --> 0~2n-2
};

// Time Complexity: O(N!)
// Space Complexity: O(N)
Time O(N!) Space O(N)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern