LeetCode-N-Queens
2013-09-14 00:28
274 查看
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
There exist two distinct solutions to the 4-queens puzzle:
'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: int check(int* X,int k){ for(int i=0;i<k;i++){ if(X[i]==X[k]||abs(X[i]-X[k])==abs(i-k))return -1; } return 0; } vector<vector<string> > solveNQueens(int n) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<vector<string> > ret; int* X=new int[n+1]; X[0]=-1; int j=0; while(j>=0) { X[j]++; if(X[j]==n) { j--; continue; } if(check(X,j)<0) { continue; } else { j++; if(j==n){ vector<string> result; for(int i=0;i<n;i++){ string s; s.resize(n,'.'); s[X[i]]='Q'; result.push_back(s); } ret.push_back(result); j--; } else { X[j]=-1; } } } delete X; return ret; } };
相关文章推荐
- [LeetCode]N-Queens
- N-Queens -- leetcode
- N-Queens--LeetCode
- LeetCode51——N-Queens
- leetcode: N-Queens
- 129_leetcode_N-Queens
- LeetCode: N-Queens
- N-Queens leetcode java
- LeetCode 51. N-Queens--Python实现
- Leetcode: N-Queens
- LeetCode 051 N-Queens
- leetcode: 51. N-Queens
- LeetCode N-Queens
- leetcode--n_queens&&n_queens_II
- leetcode: N-Queens
- 【LeetCode】N-Queens
- LeetCode(N-Queens)
- leetcode—N-Queens系列
- LeetCode - N-Queens I && II
- [leetcode]N-Queens