本文共 889 字,大约阅读时间需要 2 分钟。
题目:
解答:
输出可行解个数。参见上一篇博客。
代码:
class Solution { public: int totalNQueens(int n) { int res = 0; vectortemp; search(0, n, temp, res); return res; } private: void search(int level, int n, vector &temp, int &res) { if (level == n) { ++res; return; } string str (n, '.'); for(int i = 0; i < n; i++) { str[i] = 'Q'; if (judge(i, temp)) { temp.push_back(str); search(level + 1, n, temp, res); temp.pop_back(); } str[i] = '.'; } } bool judge(int pos, vector &temp) { for (int i = 0; i < temp.size(); i++) { if (temp[i][pos] == 'Q') { return false; } for (int j = 0; j < temp[i].length(); j++) { if (temp[i][j] == 'Q') { if (abs(int(temp.size()) - i) == abs(j - pos)) return false; } } } return true; } };
转载地址:http://oytsi.baihongyu.com/