Leetcode-52.N-Queens
来源:互联网 发布:心酸的句子知乎 编辑:程序博客网 时间:2024/05/04 08:33
Problem:
1. return the all configuration the vector of the chessborad
2. return the amount of of distinct solution
Analysis:
The idea is using DFS search with backtracking in recursive.
We use a 1D vector(n, 0) to store the position of Queen in each row.
Starting the first row, try each column. If it’s valid,we move to the next row and try each column. If the position will induce attack. we try next column. If can’t find a valid position in the current row, we backtrack to the previous row and try next next column.
Solution of problem 1:
class Solution { public: vector< vector <string> > solveNQueens(int n) { vector<vector<string> > res; vector<int> v(n, 0); helper(n, 0, res, v); return res; } void helper(int n, int start, vector<vector<string> >& res, vector<int>& v) { if (start == n) { res.push_back(toStr(v)); return; } for (int index = 0; index < n; ++index) { v[start] = index; if (isValid(v, start)) helper(n, start + 1, res, v); } } bool isValid(vector<int> & v, int n) { for (int i = 0; i < n; i++) { if(abs(n - i) == abs(v[n] - v[i]) || v[i] == v[n]) return 0; } return 1; } vector<string> toStr(vector<int>& v){ int n = v.size(); vector<string> rel; for (int i = 0; i < n; ++i) { string t(n, '.'); t[v[i]] = 'Q'; rel.push_back(t); } return rel; }};
Solution of problem 2 :
class Solution {public: int totalNQueens(int n) { int count = 0; vector<int> v(n, 0); helper(n, 0, count, v); return count;}void helper(int n, int start, int& count, vector<int>& v){ if (start == n) { count++; return; } for (int i = 0; i < n; ++i) { v[start] = i; if (isValid(v, start)) helper(n, start + 1, count, v); }} bool isValid(vector<int>& v, int start) { for (int i = 0; i < start; ++i) if (abs(i - start) == abs(v[i] - v[start]) || v[i] == v[start]) return 0; return 1; }};
0 0
- Leetcode-52.N-Queens
- LeetCode 52. N-Queens II
- LeetCode --- 52. N-Queens II
- LeetCode 52.N-Queens II
- [Leetcode] 52. N-Queens II
- [leetcode] 52.N-Queens II
- [leetcode] 52. N-Queens II
- LeetCode 52. N-Queens II
- leetcode 52. N-Queens II
- LeetCode-51&52.N-Queens
- LeetCode 52. N-Queens II
- LeetCode 52. N-Queens II
- leetcode.52. N-Queens II
- LeetCode 52. N-Queens II
- [LEETCODE]52. N-Queens II
- [LeetCode] 52. N-Queens II
- leetcode 52. N-Queens II
- leetcode-52. N-Queens II
- 对SPEA算法的一些总结
- linux下根目录切换隔离chroot工具小结
- 【Linux探索之旅】第四部分第四课:分析网络,隔离防火
- android application
- 黑马程序员-C语言-文件
- Leetcode-52.N-Queens
- 结构体指针 & 结构体嵌套使用...
- 枚举(enum)的使用
- 12306出现了这么多年为何还是如此渣
- juqery中checkbox的click事件
- typedef的使用...typedef int (*Func)(int,int); Func func = sum;
- 预处理...
- Bug:"XXXView" nib but the view outlet was not set
- 2015年总结