class Solution {
/**
* Get all distinct N-Queen solutions
* @param n: The number of queens
* @return: All distinct solutions
* For example, A string '...Q' shows a queen on forth position
*/
ArrayList<ArrayList
// write your code here
ArrayList
ArrayList<ArrayList
if( n<0 )
return result;
int cols[] = new int[n];
DFS_helper(n,result,0,cols);
return result;
}
public void DFS_helper(int nQueens,ArrayList<ArrayList<String>> result,int row,int[] cols){
if(row == nQueens ){
ArrayList<String> path = new ArrayList<String>();
for(int i = 0;i<nQueens ;i++){
String s = "";
for(int j = 0;j< nQueens ;j++){
if(j == cols[i])
s = s + "Q";
else
s = s + ".";
}
path.add(s);
}
result.add(path);
}else{
for(int i = 0;i<nQueens ;i++){
cols[row] = i;
if(isValid(row,cols))
DFS_helper(nQueens,result,row + 1 ,cols);
}
}
}
public boolean isValid(int row ,int[] cols){
for(int i=0;i<row;i++){
if(cols[row] == cols[i] || Math.abs(cols[row] - cols[i]) == row - i)
return false;
}
return true;
}
};