标签:
// 没有太大意义,和51题重复,只需要计数或者输出vector的大小即可
1 class Solution { 2 public: 3 int totalNQueens(int n) { 4 vector<vector<string>> result; 5 vector<int> pos(n, -1); 6 vector<int> isColumnSafe(n, 1); 7 vector<int> isDiag1Safe(2 * n - 1, 1); // 主对角线 8 vector<int> isDiag2Safe(2 * n - 1, 1); // 斜对角线 9 checkPos(result, pos, isColumnSafe, isDiag1Safe, isDiag2Safe, 0, n); 10 return result.size(); 11 } 12 private: 13 void checkPos( 14 vector<vector<string>>& result, 15 vector<int>& pos, 16 vector<int>& isColumnSafe, 17 vector<int>& isDiag1Safe, 18 vector<int>& isDiag2Safe, 19 int i, 20 int n 21 ) 22 { 23 for (int j = 0; j < n; ++j) { 24 bool flag = isColumnSafe[j] && isDiag1Safe[i - j + n - 1] && isDiag2Safe[i + j]; 25 if (flag) { 26 isColumnSafe[j] = 0; 27 isDiag1Safe[i - j + n - 1] = 0; 28 isDiag2Safe[i + j] = 0; 29 pos[i] = j; 30 if (i == n - 1) { 31 vector<string> vec(n, string(n, ‘.‘)); 32 int cnt = 0; 33 for (int k = 0; k < n; ++k) { 34 vec[cnt ++][pos[k]] = ‘Q‘; 35 } 36 result.push_back(vec); 37 for (int i = 0; i < n; ++i) { 38 cout << vec[i] << endl; 39 } 40 cout << endl; 41 } 42 else { 43 checkPos(result, pos, isColumnSafe, isDiag1Safe, isDiag2Safe, i + 1, n); 44 } 45 isColumnSafe[j] = 1; 46 isDiag1Safe[i - j + n - 1] = 1; 47 isDiag2Safe[i + j] = 1; 48 } 49 } 50 } 51 };
标签:
原文地址:http://www.cnblogs.com/shadowwalker9/p/5845608.html