[LeetCode] N-Queens
2012-11-13 10:58
288 查看
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
For example,
There exist two distinct solutions to the 4-queens puzzle:
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.."] ] DFS to solve it!
class Solution { private: vector<vector<string> > ret; int a[100]; bool canUse[100]; public: bool check(int y, int n) { for(int i = 0; i < n; i++) if (abs(i - n) == abs(y - a[i])) return false; return true; } void solve(int dep, int maxDep) { if (dep == maxDep) { vector<string> ans; for(int i = 0; i < maxDep; i++) { string s; for(int j = 0; j < a[i]; j++) s += '.'; s += 'Q'; for(int j = 0; j < maxDep - (a[i] + 1); j++) s += '.'; ans.push_back(s); } ret.push_back(ans); return; } for(int i = 0; i < maxDep; i++) if (canUse[i] && check(i, dep)) { canUse[i] = false; a[dep] = i; solve(dep + 1, maxDep); canUse[i] = true; } } vector<vector<string> > solveNQueens(int n) { // Start typing your C/C++ solution below // DO NOT write int main() function ret.clear(); memset(canUse, true, sizeof(canUse)); solve(0, n); return ret; } };
相关文章推荐
- [leetcode-51]N-Queens(java)
- LeetCode--N-Queens
- LeetCode – Refresh – N-Queens
- [LeetCode]N-Queens
- N-Queens [Leetcode解题报告]
- LeetCode第51题之 N-Queens
- LeetCode N-Queens
- leetcode 51 N-Queens 回溯 万能结构
- LeetCode题解:N-Queens I and II
- Leetcode 51. N-Queens
- LeetCode 51 N-Queens
- Leetcode N-Queens
- [LeetCode] N-Queens
- LeetCode 51. N-Queens(N皇后)
- 52. N-Queens II Leetcode Python
- [Leetcode 91] 51 N-Queens
- LeetCode-51. N-Queens (JAVA)(打印N皇后解集)
- leetcode N-Queens & N-Queens II
- Leetcode 51. N-Queens
- LeetCode-51-N-Queens 八皇后问题dfs