N-Queens DFS
2015-07-06 10:27
453 查看
思路:
典型的DFS。时间复杂度O(N!),空间复杂度O(N)。
每一层有n种放置方法,一共有n层。
典型的DFS。时间复杂度O(N!),空间复杂度O(N)。
map[row]表示第
irow行的皇后放置的位置。
每一层有n种放置方法,一共有n层。
//N-Queens : dfs class Solution { private: vector<vector<string>> res; void addSolution(vector<int> &map, int n) { vector<string> ans; for(int i = 0; i < n; ++i) { string row(n, '.'); row[map[i]] = 'Q'; ans.push_back(row); } res.push_back(ans); } bool canSet(vector<int> &map, int n, int row, int col) { //if(map[row] != 0) //row // return false; int tmpcol = 0; for(int tmprow = 0; tmprow < row; ++tmprow) { tmpcol = map[tmprow]; if(tmpcol == col) //col return false; if((tmpcol - col) == (tmprow - row)) //right slant line return false; if((tmpcol - col) == (row - tmprow)) //left slant line return false; } return true; } void nqueensSet(vector<int> &map, int n, int row) { for(int i = 0; i < n; ++i) { if(canSet(map, n, row, i)) { map[row] = i; if(row == n-1) { addSolution(map, n); map[row] = 0; return; } nqueensSet(map, n, row+1); map[row] = 0; } } } public: vector<vector<string>> solveNQueens(int n) { vector<int> map = vector<int>(n, 0); //judge and set nqueensSet(map, n, 0); return res; } };
相关文章推荐
- Arduino Uno 在win7 64位下的驱动问题
- DAX Tabular Calculate,Filter,Value和All
- 优先队列priority_queue 用法详解
- UIDynamicAnimator 小结
- 从源代码的角度聊聊java中StringBuffer、StringBuilder、String中的字符串拼接
- 从源代码的角度聊聊java中StringBuffer、StringBuilder、String中的字符串拼接
- ScrollView中添加一个android:fillViewport="true"(转)
- (PHP 5.3 and above) Please set ‘request_order’ ini value to include C,G and P (recommended: ‘CGP’) i
- [SoapUI] 获取Cookie,并循环遍历当前Project下所有的Test Suite,Test Case,Test Step,将Cookie传递给这些Test Step
- unique-paths
- 详解 UIView 的 Tint Color 属性
- 自定义UI之ActionBar
- Ubuntu更新包管理器失败:Requires installation of untrusted packages问题解决
- Sequence Assignments FRM-41830: List of Value contains no entries.
- 如何自定义 UIPickerView 的行?
- UiAutomator学习笔记
- UIImagePickerController全屏
- iOS笔记056 - UI总结02
- UIActivityIndicatorView
- SeaJS与 RequireJS 的异同