题目:
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.."] ]解法:
N皇后问题,用最经典的回溯法求解
这里按照列的顺序来求解,试探当前这一列的Q的位置
1、若Q放在当前的位置是合法的,则试探第二列的Q的位置
2、如果Q放在当前位置是不合法的,则尝试下一种可能,如果这一列中没有合法的Q的位置,则返回到上一列的状态,继续试探
那么如和判断某个皇后的放置位置是否合法呢?只需要查找这一列之前的行,斜线方向有没有放置过Q即可
代码如下:
import java.util.ArrayList;
import java.util.List;
public class No50_NQueens {
public static void main(String[] args){
System.out.println(solveNQueens(4));
}
public static List<String[]> solveNQueens(int n) {
List<String[]> ret = new ArrayList<String[]>();
if(n > 0){
char[][] element = new char[n][n];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
element[i][j] = '.';
solve(ret, element, n, 0);
}
return ret;
}
public static void solve(List<String[]> list, char[][] C, int n, int col){
for(int i=0;i<n;i++){
C[i][col] = 'Q';
if(isLegal(C, i, col)){
if(col == n-1){
String[] S = new String[n];
for(int k=0;k<n;k++)
S[k] = String.valueOf(C[k]);
list.add(S);
C[i][col] = '.';
continue;
}
solve(list, C, n, col+1);
}
C[i][col] = '.';
}
return;
}
public static boolean isLegal(char[][] C, int row, int col){
for(int j=0;j<col;j++){
if(C[row][j] == 'Q')
return false;
}
for(int i=row-1,j=col-1;i>=0&&j>=0;i--,j--){
if(C[i][j] == 'Q')
return false;
}
for(int i=row+1,j=col-1;i<C.length&&j>=0;i++,j--){
if(C[i][j] == 'Q')
return false;
}
return true;
}
}