2017.9.18
呵呵,直到今天才知道皇后问题是什么问题。
就是不可以同行同列同斜线。
采用回溯法,一个一个试,就可以了。
public class Solution {
/*
* @param n: The number of queens
* @return: All distinct solutions
*/
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 List<String> toString(char [][]arr){
List<String> list = new LinkedList<String>();
int length = arr.length;
String res = "";
for(int i = 0; i < length;i++){
res = "";
for(int j = 0; j < length; j++){
if(arr[i][j] == 'Q'){
res += "Q";
}
else{
res += ".";
}
}
list.add(res);
}
return list;
}
public static List<List<String>> solveNQueens(int n,char [][]arr,int k,List<List<String>> res) {
// 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){
List<String> str = toString(arr_tmp);
res.add(str);
}
else{
solveNQueens(n,arr_tmp,k+1,res);
}
}
}
return res;
}
public static List<List<String>> solveNQueens(int n) {
// write your code here
char [][]arr = new char[n][n];
for(int i = 0; i< n; i++){
for(int j = 0;j < n;j++){
arr[i][j] = '.';
}
}
List<List<String>> res = new LinkedList<>();
res = solveNQueens(n,arr,0,res);
return res;
}
}