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.."] ]
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; } };