fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4. class Solution {
  5. public:
  6. void solve(int i, int& n, vector<string>& tmp, vector<vector<string>>& ans, vector<bool>& c, vector<bool>& md, vector<bool>& td) {
  7. if (i == n) {
  8. ans.push_back(tmp);
  9. return;
  10. }
  11. string str(n, '.');
  12. for (int j = 0; j < n; j++) {
  13. if ((c[j] == false && md[i - j + n] == false && td[i + j] == false)) {
  14. str[j] = 'Q';
  15. c[j] = true;
  16. md[i - j + n] = true;
  17. td[i + j] = true;
  18. tmp.push_back(str);
  19. solve(i + 1, n, tmp, ans, c, md, td);
  20. tmp.pop_back();
  21. str[j] = '.';
  22. c[j] = false;
  23. md[i - j + n] = false;
  24. td[i + j] = false;
  25. }
  26. }
  27. }
  28. int totalNQueens(int n) {
  29. vector<vector<string>> ans;
  30. vector<string> tmp;
  31. vector<bool> c(n, false), md(2 * n + 3, false), td(2 * n + 3, false);
  32. solve(0, n, tmp, ans, c, md, td);
  33. return ans.size();
  34. }
  35. };
  36.  
  37. int main() {
  38. int n = 1;
  39. Solution s;
  40. int totalSolutions = s.totalNQueens(n);
  41. cout << "Total number of solutions for " << n << " queens: " << totalSolutions << endl;
  42. return 0;
  43. }
  44.  
Success #stdin #stdout 0s 5308KB
stdin
Standard input is empty
stdout
Total number of solutions for 1 queens: 1