← Home

51. N-Queens

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
backtrackingC++Markdown
51

This is one of those problems where the clean idea matters more than the amount of code. For 51. N-Queens, the solution in this repository is mainly a backtracking solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: backtracking.

The notes already sitting in the source point us in the right direction:

  • Backtracking

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are backtrack, row, used_col, used_pos_diag, used_neg_diag.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Backtracking
02//Runtime: 12 ms, faster than 59.92% of C++ online submissions for N-Queens.
03//Memory Usage: 8 MB, less than 32.76% of C++ online submissions for N-Queens.
04class Solution {
05public:
06    int n;
07    
08    void backtrack(vector<bool>& used_col, vector<bool>& used_pos_diag, 
09                   vector<bool>& used_neg_diag, int r, 
10                   vector<int>& curpos, vector<vector<string>>& ans){
11        if(r == n){
12            vector<string> curans;
13            for(int i = 0; i < n; ++i){
14                string row(n, '.');
15                row[curpos[i]] = 'Q';
16                curans.push_back(row);
17            }
18            ans.push_back(curans);
19        }else{
20            for(int c = 0; c < n; ++c){
21                if(!used_col[c] && !used_pos_diag[r-c+n-1] && !used_neg_diag[r+c]){
22                    curpos.push_back(c);
23                    used_col[c] = true;
24                    used_pos_diag[r-c+n-1] = true;
25                    used_neg_diag[r+c] = true;
26                    
27                    backtrack(used_col, used_pos_diag, used_neg_diag, r+1, curpos, ans);
28                    
29                    used_col[c] = false;
30                    used_pos_diag[r-c+n-1] = false;
31                    used_neg_diag[r+c] = false;
32                    curpos.pop_back();
33                }
34            }
35        }
36    };
37    
38    vector<vector<string>> solveNQueens(int n) {
39        this->n = n;
40        vector<int> curpos;
41        vector<vector<string>> ans;
42        //in each recursion, r is different, so there must be only one Q in a row
43        //for each row, need to check if that column is used
44        vector<bool> used_col(n, false);
45        //also check if that positive diagonals is used
46        //there are 2*n-1 positive diagonals
47        vector<bool> used_pos_diag(2*n-1, false);
48        //also check if that positive diagonals is used
49        //there are 2*n-1 negative diagonals
50        vector<bool> used_neg_diag(2*n-1, false);
51        
52        backtrack(used_col, used_pos_diag, used_neg_diag, 0, curpos, ans);
53        
54        return ans;
55    }
56};
57
58//+speed up, vector<bool> -> vector<int>, build ans on the fly
59//https://leetcode.com/problems/n-queens/discuss/19808/Accepted-4ms-c%2B%2B-solution-use-backtracking-and-bitmask-easy-understand
60//Runtime: 0 ms, faster than 100.00% of C++ online submissions for N-Queens.
61//Memory Usage: 7.2 MB, less than 91.99% of C++ online submissions for N-Queens.
62class Solution {
63public:
64    int n;
65    
66    void backtrack(vector<int>& used, int r, 
67                   vector<string>& cur, vector<vector<string>>& ans){
68        if(r == n){
69            ans.push_back(cur);
70        }else{
71            for(int c = 0; c < n; ++c){
72                if(!used[c] && !used[n+r-c+n-1] && !used[n+2*n-1+r+c]){
73                    cur[r][c] = 'Q';
74                    used[c] = used[n+r-c+n-1] = used[n+2*n-1+r+c] = true;
75                    
76                    backtrack(used, r+1, cur, ans);
77                    
78                    used[c] = used[n+r-c+n-1] = used[n+2*n-1+r+c] = false;
79                    cur[r][c] = '.';
80                }
81            }
82        }
83    };
84    
85    vector<vector<string>> solveNQueens(int n) {
86        this->n = n;
87        vector<string> cur(n, string(n, '.'));
88        vector<vector<string>> ans;
89        vector<int> used(n + 2*n-1 + 2*n-1, false);
90        
91        backtrack(used, 0, cur, ans);
92        
93        return ans;
94    }
95};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.