递归+回溯,不多说了。唯一要注意的是在每次记录一个可行的方案时,要复制一份数组,在Java中可以通过
1 循环复制
2 clone() 方法
3 System.arraycopy() 方法
这里按照书上,用了clone()方法!
package Recursion;
import java.util.ArrayList;
/**
* Write an algorithm to print all ways of arranging eight queens on a chess board so that none of them share the same row, column or diagonal.
译文:
经典的八皇后问题,即在一个8*8的棋盘上放8个皇后,使得这8个皇后无法互相攻击( 任意2个皇后不能处于同一行,同一列或是对角线上),输出所有可能的摆放情况。
*
*/
public class S9_9 {
public static int GRID_SIZE = 8;
public static void main(String[] args) {
ArrayList<Integer[]> results = new ArrayList<Integer[]>();
Integer[] columns = new Integer[GRID_SIZE];
clear(columns);
placeQueens(0, columns, results);
printBoards(results);
System.out.println(results.size());
}
// column = columns[row]
public static void placeQueens(int row, Integer[] columns, ArrayList<Integer[]> results) {
if(row == GRID_SIZE){
results.add(columns.clone()); // 注意这里要做一个复制!
return;
}
for(int col=0; col<GRID_SIZE; col++){
if(isValid(row, col, columns)){
columns[row] = col;
placeQueens(row+1, columns, results);
columns[row] = -1;
}
}
}
public static boolean isValid(int row, int col, Integer[] columns){
if(columns[row] != -1){
return false;
}
for(int r=0; r<row; r++){
if(columns[r] == col){
return false;
}
if(Math.abs(r-row) == Math.abs(columns[r]-col)){
return false;
}
}
return true;
}
public static void clear(Integer[] columns) {
for (int i = 0; i < GRID_SIZE; i++) {
columns[i] = -1;
}
}
public static void printBoards(ArrayList<Integer[]> boards) {
for (int i = 0; i < boards.size(); i++) {
Integer[] board = boards.get(i);
printBoard(board);
}
}
public static void printBoard(Integer[] columns) {
System.out.println("-----------------");
for(int i = 0; i < GRID_SIZE; i++){
System.out.print("|");
for (int j = 0; j < GRID_SIZE; j++){
if (columns[i] == j) {
System.out.print("Q|");
} else {
System.out.print(" |");
}
}
System.out.println("\n-----------------");
}
System.out.println("");
}
}