N-Queens
Description:
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.."] ]
Code:
class Solution { public: int x[100]; bool place(int k)//考察皇后k放置在x[k]列是否发生冲突 { int i; for(i=1;i<k;i++) if(x[k]==x[i]||abs(k-i)==abs(x[k]-x[i])) return false; return true; } vector<string> toVectorString(int n) { vector<string>result; for (int i = 1; i <= n; ++i) { string str(n,'.'); str[x[i]-1]='Q'; result.push_back(str); } return result; } vector<vector<string>> solveNQueens(int n) { vector< vector<string> >result; for(int i=1;i<=n;i++) x[i]=0; int k=1; while(k>=1) {//x[1]...x[n]表示第k个皇后在第x[k]列 x[k]=x[k]+1; //在下一列放置第k个皇后 while(x[k]<=n&&!place(k)) x[k]=x[k]+1;//搜索下一列 if(x[k]<=n&&k==n)//得到一个输出 { vector<string>temp = toVectorString(n); result.push_back(temp); } else if(x[k]<=n&&k<n) k=k+1;//放置下一个皇后 else { x[k]=0;//重置x[k],回溯 k=k-1; } } return result; } };