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.."] ]
LL's solution:
DFS
public class Solution {
static ArrayList<String[]> res = new ArrayList<String[]>();
public boolean isValid(int row,int col,char[][] board,char c,int n){
boolean valid = true;
if(c=='Q'){
for(int i = 0;i<n;i++){
//check row
if(board[row][i]=='Q' && i!=col){
valid = false;
break;
}
//check col
if(board[i][col]=='Q' && i!=row){
valid = false;
break;
}
}
//check diagonal: \
if(valid){
int row_s=row,col_s=col;
while(row_s>0 && col_s>0){
row_s--;
col_s--;
}
while(row_s<n && col_s<n){
if(board[row_s][col_s] == 'Q' && row_s!=row){
valid = false;
break;
}
else{
row_s++;
col_s++;
}
}
}
//check diagonal: /
if(valid){
int row_s=row,col_s=col;
while(row_s<n-1 && col_s>0){
row_s++;
col_s--;
}
while(row_s>=0 && col_s<n){
if(board[row_s][col_s] == 'Q' && row_s!=row){
valid = false;
break;
}
else{
row_s--;
col_s++;
}
}
}
}
return valid;
}
public boolean DFS(int row,int col,int n,char c,int counter,char[][] board){
boolean valid=false;
if(isValid(row,col,board,c,n)){ // check if board is valid
board[row][col] = c;
if(row ==n-1 && col == n-1){ // if borad is filled
if(counter==n){
//res.add(board);
String[] tmp = new String[n];
for(int i = 0;i<n;i++){
String s = "";
for(int j = 0;j<n;j++){
s += board[i][j];
}
tmp[i] = s;
}
res.add(tmp);
//valid = true;
//return valid;
} // else valid = false
}
else{ // fill the next spot
if(col<n-1)
col++;
else{
col=0;
row++;
}
//try fill q
valid = DFS(row,col,n,'Q',counter+1,board);
if(!valid)
valid = DFS(row,col,n,'.',counter,board);
}
}
return valid;
}
public ArrayList<String[]> solveNQueens(int n) {
// Start typing your Java solution below
// DO NOT write main() function
char[][] board = new char[n][n];
boolean valid;
res.clear();
valid = DFS(0,0,n,'Q',1,board);
if(!valid)
DFS(0,0,n,'.',0,board);
return res;
}
}
Note:
1.queen attack要check横,竖,及两个斜向。注意,反斜向(/)row可以减到等于0!
2.当发现一个valid的solution的时候,不能直接return,否则只会记录当前solution,终止recursion,不会继续try别的分支了。
3.开始recursion的时候注意要试‘Q’,然后还要include第一个格为‘.’的情况。