首页 > 代码库 > 052.N-Queens II
052.N-Queens II
// 没有太大意义,和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 n21 )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 };
052.N-Queens II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。