51. N-Queens, leetcode
来源:互联网 发布:音频压缩算法 编辑:程序博客网 时间:2024/05/28 18:45
题目:
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q'
and '.'
both indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."]]
代码及思路:(回溯的递归方法)15ms AC
class Solution {public:int place(int k)//k 表示行数;函数的意思是,查看(k,x[k])是否可以放皇后{for (int i = 0; i < k ; i++)//当前行是k - 1if (abs(k - i) == abs(x[k] - x[i]) || x[i] == x[k]) return 0;return 1;}void Backtrak(int t){if (t > n - 1){sum++;vector<string> temp;string a(n,'.');for(auto p : x){ a[p] = 'Q'; temp.push_back(a); a[p] = '.';}ans.push_back(temp);}else{for (int i = 0; i < n; i++){x[t] = i;if (place(t))Backtrak(t + 1);}}}vector<vector<string>> solveNQueens(int in) {vector<int> vec(in, -1);x = vec;n = in;Backtrak(0);return ans;}private:vector<int> x;//注意1:这里不能写作vector<int> x(); 否则认为x是一个函数;并且在这里对x进行初始化也将报错。int n;//注意2:这里n是可以初始化的int sum = 0;vector<vector<string>> ans;};
代码及思路2:(回溯的栈方法)
待续
总结:
1,对于回溯问题,最好找一个数据结构存储解的集合。比如这里的x[i],表示第i行的第j列可以放皇后。即用
数组存储每行皇后的位置
2,其中一个微小笔误,浪费了好长时间去排查。为什么用这么长时间才排查出来,是因为排查方法不当,
所以以后写代码出现错误,不要害怕,打开IDE设置合适的断点,很容易就可以找出来的。
0 0
- LeetCode 51. N-Queens
- LeetCode --- 51. N-Queens
- LeetCode 51.N-Queens
- [Leetcode] 51. N-Queens
- [leetcode] 51.N-Queens
- [leetcode] 51. N-Queens
- LeetCode 51. N-Queens
- leetcode 51. N-Queens
- 【LeetCode】51. N-Queens
- leetcode 51. N-Queens
- LeetCode 51. N-Queens
- LeetCode 51. N-Queens
- leetcode.51. N-Queens
- Leetcode 51. N-Queens
- LeetCode 51. N-Queens
- [LeetCode] 51. N-Queens
- leetcode 51. N-Queens
- leetcode-51. N-Queens
- 朴素贝叶斯分类的实现
- 基于BP神经网络的数据分类
- canvas绘制电子时钟
- FAILED Binder Transaction 问题的原因及解决方案
- Redis系列~数据备份与恢复(十三)
- 51. N-Queens, leetcode
- plsql数据导入导出的使用
- Nginx 完整配置说明
- android DownloadManager使用方法
- bootstrap-面板
- Android 调用系统相机拍照保存以及调用系统相册的方法
- Redis系列~安全(十四)
- angularJs表单验证问题
- c++primer第一章小结-1