LeetCode N-Queens
2014-12-03 21:08
260 查看
又是一个八皇后问题:
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) { this->N=n; memset(matrix,0,sizeof(matrix)); dfs(0); return d; } int check(int x,int y) { for(int j=0;j<y;++j) if(matrix[x][j]==1)return 0; for(int i=0;i<N;++i) for(int j=0;j<y;++j) { if(abs(i-x)==abs(j-y)&&matrix[i][j]==1)return 0; } return 1; } void dfs(int j) { if(j==N) { //存储 vector<string>mt; for(int i=0;i<N;++i){ string td; for(int j=0;j<N;++j) { if(matrix[i][j]==0)td+='.'; if(matrix[i][j]==1)td+='Q'; } mt.push_back(td); } d.push_back(mt); return ; } for(int i=0;i<N;++i) { if(matrix[i][j]==0&&check(i,j)) { matrix[i][j]=1; dfs(j+1); matrix[i][j]=0; } } } private : int N; vector<vector<string> > d; int matrix[100][100]; };
相关文章推荐
- LeetCode51 N-Queens
- LeetCode-51. N-Queens和LeetCode-52. N-Queens II
- N皇后回溯解法 leetcode N-Queens
- 【LeetCode】N-Queens
- LeetCode 51. N-Queens
- Leetcode: N-Queens
- [LeetCode] N-Queens
- leetcode-N-Queens 搜索
- leetcode N-Queens
- Leetcode 51. N-Queens (Hard) (cpp)
- N-Queens [Leetcode解题报告]
- leetcode: N-Queens
- 129_leetcode_N-Queens
- 【leetcode】N-Queens I & II
- N-Queens leetcode java
- LeetCode 51. N-Queens(N皇后)
- LeetCode Online Judge 题目C# 练习 - N-Queens
- Leetcode -- N-Queens
- leetcode: N-Queens
- leetcode—N-Queens系列