Advertisement
spider68

N-Queens II

May 30th, 2021
1,246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.88 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int totalNQueens(int n) {
  4.         vector<bool> col(n, true);
  5.         vector<bool> anti(2*n-1, true);
  6.         vector<bool> main(2*n-1, true);
  7.         vector<int> row(n, 0);
  8.         int count = 0;
  9.         dfs(0, row, col, main, anti, count);
  10.         return count;
  11.     }
  12.     void dfs(int i, vector<int> &row, vector<bool> &col, vector<bool>& main, vector<bool> &anti, int &count) {
  13.             if (i == row.size()) {
  14.                 count++;
  15.                 return;
  16.             }
  17.            for (int j = 0; j < col.size(); j++) {
  18.              if (col[j] && main[i+j] && anti[i+col.size()-1-j]) {
  19.                  row[i] = j;
  20.                  col[j] = main[i+j] = anti[i+col.size()-1-j] = false;
  21.                  dfs(i+1, row, col, main, anti, count);
  22.                  col[j] = main[i+j] = anti[i+col.size()-1-j] = true;
  23.           }
  24.         }
  25.     }
  26. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement