八皇后问题
八皇后问题,是一个古老而著名的问题,是回溯算法的典型案例。该问题是国际西洋棋棋手马克斯·贝瑟尔于1848年提出:在8×8格的国际象棋上摆放八个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,问有多少种摆法。 高斯认为有76种方案。1854年在柏林的象棋杂志上不同的作者发表了40种不同的解,后来有人用图论的方法解出92种结果。八皇后问题可以推广为更一般的n皇后摆放问题:这时棋盘的大小变为n1×n1,而皇后个数也变成n2。而且仅当 n2 ≥ 1 或 n1 ≥ 4 时问题有解。
递归:
public class EightQueen {
private static int count=0; //记录第几种可能
private static int N=8;
public static void main(String[] args) {
int[][] arr=new int[N][N]; //默认元素为0 1当皇后
eightQueen(0,arr); //打印八皇后所有可能的解 并且从第一行开始 0
}
//row [0,7]
private static void eightQueen(int row, int[][] arr) {
if(row==N){//打印条件,假设是8皇后,每次走到第9行时就打印。
count++;
System.out.println("第"+count+"种:");
for(int i=0;i<arr.length;i++){
for(int j=0;j<arr[i].length;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}else{
//做一个数组备份
int[][] newArr=new int[N][N];
for(int i=0;i<arr.length;i++){
for(int j=0;j<arr[i].length;j++){
newArr[i][j]=arr[i][j];
}
}
for(int col=0;col<N;col++){
/*
判断当前元素的上,左上,右上是否有皇后。
*/
if(noDangerous(row,col,newArr)){
for(int c=0;c<N;c++){
newArr[row][c]=0;//将当前行的其他位置的皇后置为0
}
newArr[row][col]=1;
eightQueen(row+1, newArr);
}
}
}
}
private static boolean noDangerous(int row, int col, int[][] newArr) {
//正上
for(int r=row-1;r>=0;r--){
if(newArr[r][col]==1){
return false;
}
}
//左上
for(int r=row-1,c=col-1;r>=0&&c>=0;r--,c--){
if(newArr[r][c]==1){
return false;
}
}
//右上
for(int r=row-1,c=col+1;r>=0&&c<N;r--,c++){
if(newArr[r][c]==1){
return false;
}
}
return true;
}
}