The n-queens puzzle is the problem of placing n queens on an n×nchessboard 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.
分析:查阅相关资料,得知需要行,列以及对角线都只有一个皇后
那么接下来就是遍历的过程,每次放置一个皇后,都要确定他的合法性
大神的妙用: 由于每行只有一个皇后,那么可以建立一个一维数组,代表每行那个唯一的皇后的位置
import java.util.*;
public class Solution {
ArrayList<String[]> result=new ArrayList<>();
public ArrayList<String[]> solveNQueens(int n) {
if(n<=0){
return result;
}
int[] cols=new int[n];
for(int i=0;i<n;i++){
cols[0]=i;
dfs(cols,1);
}
return result;
}
public void dfs(int[] cols,int row){
//当相等时,就证明已经产生了一个可行解
if(row==cols.length){
String[] str=new String[cols.length];
for(int i=0;i<str.length;i++){
str[i]="";
for(int j=0;j<str.length;j++){
if(j==cols[i]){
str[i]+="Q";
}else{
str[i]+=".";
}
}
}
result.add(str);
return;
}
//判断row行的第i列是否符合,若符合,设置当前行皇后的坐标 继续判断下一行
for(int i=0;i<cols.length;i++){
if(isOK(cols,row,i)){
cols[row]=i;
dfs(cols,row+1);
}
}
}
//进行判断合法性 是否同一列,是否对角线
public boolean isOK(int[] cols,int row,int col){
if(cols==null){
return false;
}
for(int i=0;i<row;i++){
if(cols[i]==col||Math.abs(cols[i]-col)==Math.abs(row-i)){
return false;
}
}
return true;
}
}