[LeetCode] N-Queens
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 '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,回溯法
首先实现了一个n皇后的dfs,X[i] 表示第i行所处的位置
#define N 4 vector<int> x; bool checkTwoPoints(int i, int j, int xi, int xj) { //cout << "check i\t" << i << endl; //cout << "check j\t" << j << endl; if(xi == xj) // same column return false; if( abs(xi-xj) == abs(i-j)) // diag return false; return true; } bool check(vector<int> x, int n) // check x[n] and x[0 .. n-1] { for(int i = 0; i < n; i++) { if(!checkTwoPoints(i, n, x[i], x[n])) return false; } return true; } void dfs(int n) { if(n == N) printVector(x); for(int i = 0; i < N; i++) { x[n] = i; // check if x[n] is available if(check(x, n)) dfs(n+1); } } int main() { x.resize(N); dfs(0); #if 0 Solution sl; printVector (sl.plusOne(a)); cout <<endl<< "==============" <<endl; a.clear(); #endif return 0; }
然后考虑按照其格式打印字符串
class Solution { vector<int> x; vector< vector<string> > m_res; bool checkTwoPoints(int i, int j, int xi, int xj) { //cout << "check i\t" << i << endl; //cout << "check j\t" << j << endl; if(xi == xj) // same column return false; if( abs(xi-xj) == abs(i-j)) // diag return false; return true; } bool check(vector<int> x, int n) // check x[n] and x[0 .. n-1] { for(int i = 0; i < n; i++) { if(!checkTwoPoints(i, n, x[i], x[n])) return false; } return true; } void dfs(int n) { if(n == x.size() ) { #if 1 //printVector(x); string tmpStr; vector<string> strs; strs.resize(x.size()); for(int i = 0; i < x.size(); i++) tmpStr += '.'; for(int i = 0; i < x.size(); i++) { strs[i] = tmpStr; strs[i][x[i]] = 'Q'; } m_res.push_back(strs); return; #endif } for(int i = 0; i < x.size(); i++) { x[n] = i; // check if x[n] is available if(check(x, n)) dfs(n+1); } } public: vector<vector<string> > solveNQueens(int n) { x.resize(n); dfs(0); return m_res; } };