1#include <bits/stdc++.h>23usingnamespace std;45int n, ans =0;6voiddfs(int row, vector<bool>& col, vector<bool>& dp, vector<bool>& dm){7if(row == n) { // placed all the queens(one valid solution)8 ans++;9return;10 }11//try to place a queen in each column of the current row12for(int i =0; i < n; i++){13int right_up = row + i;14int left_down = row - i + n -1; // + n - 1 to adjust for negative index15//check if it is a valid placement16if(!col[i] &&!dp[right_up] &&!dm[left_down]){17//place a queen and mark placed18 col[i] =true; dp[right_up] =true; dm[left_down] =true;19dfs(row +1, col, dp, dm); // move on to the next queen20//recite 21 col[i] =false; dp[right_up] =false; dm[left_down] =false;22 }2324 }25}26intmain(){27 ios::sync_with_stdio(0);28 cin.tie(0);29 cin >> n;30vector<bool>col(n, false), dp(2* n -1, false), dm(2* n -1, false);31dfs(0, col, dp, dm);32 cout << ans <<'\n';33return0;34}
☕
Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.
Python records executed lines and locals automatically. For selected values in any language, add // @trace i, total on its own valid line; Python uses # @trace i, total.
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.