leetcode N-Queens
2014-06-09 21:39
281 查看
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
indicate a queen and an empty space respectively.
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.."] ]
标准的回溯法,扩展了所有情况后,回溯到父节点。需要理解函数的每个参数意义。
class Solution { public: vector<vector<string> > solveNQueens(int n) { vector<vector<string>> result; vector<string> aresult(n,string(n,'.')); sub(result,aresult,0,0,n); return result; } bool place(vector<string> aresult,int kth,int pos){ int i; bool flag=true; for(i=0;i<kth;i++){ int ipos=aresult[i].find_first_of('Q'); if(ipos==pos||abs(i-kth)==abs(ipos-pos)){ flag=false; return flag; } } return flag; } void sub(vector<vector<string>> &result,vector<string> &aresult,int kth,int pos,int n){ if(kth>=n){ //因为是考虑第K个的位置,所以只有K大于n了,才能表明已经考虑了所有皇后。而且pos是将皇后放置在pos 这个位置 result.push_back(aresult); return; } int i; for(i=pos;i<n;i++){ if(place(aresult,kth,i)){ aresult[kth][i]='Q'; sub(result,aresult,kth+1,0,n); aresult[kth][i]='.'; } } } };
相关文章推荐
- LeetCode 51. N-Queens
- [LeetCode] N-Queens
- leetcode-N-Queens 搜索
- LeetCode: N-Queens
- leetcode N-Queens
- Leetcode 51. N-Queens (Hard) (cpp)
- [Leetcode] 51. N-Queens
- N-Queens [Leetcode解题报告]
- 【leetcode】N-Queens
- LeetCode 51. N-Queens(N皇后)
- Leetcode -- N-Queens
- LeetCode N-Queens
- leetcode—N-Queens系列
- LeetCode N-Queens
- leetcode[51]N-Queens
- 【leetcode刷题笔记】N-Queens
- [leetcode刷题系列]N-Queens
- LeetCode51 N-Queens
- LeetCode-51. N-Queens和LeetCode-52. N-Queens II
- N皇后回溯解法 leetcode N-Queens