2017.9.18
public class Solution {
/*
* @param n: The number of queens.
* @return: The total number of distinct solutions.
*/
public static int res;
public static int totalNQueens(int n) {
// write your code here
res = 0;
if(n == 0 || n==1){
return 1;
}
char [][]arr = new char[n][n];
for(int i = 0; i< n; i++){
for(int j = 0;j < n;j++){
arr[i][j] = '.';
}
}
res = solveNQueens(n,arr,0);
return res;
}
public static boolean judgeAround(char [][]arr,int i,int j){
//检测同一行
int n = arr.length;
for(int k = 0; k < n ; k++){
if(arr[i][k] =='Q' || arr[k][j] =='Q'){
return false;
}
}
int x = i;
int y = j;
while( x >= 0 && y >= 0){
if(arr[x][y] == 'Q'){
return false;
}
x--;
y--;
}
x = i;
y = j;
while( x >= 0 && y <= n-1){
if(arr[x][y] =='Q'){
return false;
}
x--;
y++;
}
x = i;
y = j;
while( x <= n-1 && y >= 0 ){
if(arr[x][y] == 'Q'){
return false;
}
x++;
y--;
}
x = i;
y = j;
while( x <= n-1 && y <= n-1 ){
if(arr[x][y] == 'Q'){
return false;
}
x++;
y++;
}
return true;
}
public static int solveNQueens(int n,char [][]arr,int k) {
// write your code here
if(k >= n){
return res;
}
for(int i = 0; i < n; i++){
if(judgeAround(arr,k,i) == true){
char [][]arr_tmp = new char[n][n];
for(int h = 0; h< n; h++){
for(int j = 0;j < n;j++){
arr_tmp[h][j] = arr[h][j];
}
}
arr_tmp[k][i] = 'Q';
if(k == n-1){
res = res+1;
}
else{
solveNQueens(n,arr_tmp,k+1);
}
}
}
return res;
}
}