C++ · Solution

N Queens

This C++ solution uses graph traversal for N Queens. Read the reasoning, inspect the code, or try your own test case below.

Backtracking & recursionGraph traversalC++34 lines
Solution151of 248
Download C++ file ↓ Search the library → Open full Code Lab ↗ Report an issue ↗

Approach

Graph traversal

N Queens: traverse the graph recursively or with an explicit stack, carrying the information needed for each component, path, or subtree.

Depth-first searchGraphs

Problem and code

Useful links.

Written by benbenyaojifen. Try the problem first, then compare your approach with the code.

View exact source file ↗
Implementation

n_queens.cpp

C++

    #include <bits/stdc++.h>
     
    using namespace std;
     
    int n, ans = 0;
    void dfs(int row, vector<bool>& col, vector<bool>& dp, vector<bool>& dm){
        if(row == n) { // placed all the queens(one valid solution)
            ans++;
            return;
        }
        //try to place a queen in each column of the current row
        for(int i = 0; i < n; i++){
            int right_up = row + i;
            int left_down = row - i + n - 1; // + n - 1 to adjust for negative index
            //check if it is a valid placement
            if(!col[i] && !dp[right_up] && !dm[left_down]){
                //place a queen and mark placed
                col[i] = true; dp[right_up] = true; dm[left_down] = true;
                dfs(row + 1, col, dp, dm); // move on to the next queen
                //recite 
                col[i] = false; dp[right_up] = false; dm[left_down] = false;
            }
     
        }
    }
    int main(){
        ios::sync_with_stdio(0);
        cin.tie(0);
        cin >> n;
        vector<bool> col(n, false), dp(2 * n - 1, false), dm(2 * n - 1, false);
        dfs(0, col, dp, dm);
        cout << ans << '\n';
        return 0;
    }
        

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗Keep studying →

Test this problem

Run your code here.

Paste your code, run a test case, compare the output, or trace selected values.

Full trace, comparison & stress testing ↗
StatusReady
Output
No run yet.
Diagnostics
No diagnostics yet.

Each run is isolated and has strict limits. Passing one test does not guarantee the judge will accept the solution.