1、8皇后的的遍历代码
package com.cn.test.algorithm;
public class Queue8 {
int[][] chessboard = new int[8][8];
int count = 0;
public void printChessboard(){
for (int [] one :chessboard){
for (int i:one){
System.out.print(i+" ");
}
System.out.println();
}
}
public boolean calculateLocation(int row){
if(row == 8){
count++;
System.out.println("成功:"+count);
printChessboard();
return true;
}
//从第一列开始尝试
for(int col = 0; col < 8 ;col++){
//本行验证成功,进行下一行
if(checkLocation(row,col)){
chessboard[row][col] = 1;
calculateLocation(row + 1);
chessboard[row][col] = 0;
}
}
return false;
}
public boolean checkLocation(int row,int col){
for (int i = 0;i<row;i++){
//判断是否在同一列
if(chessboard[i][col] == 1){
return false;
}
//判断是否在同一斜线上
// 如果在同一斜线下,则满足:|col -x|= |row -i|
if(col-(row-i) >= 0 && col-(row-i) <8){
if(chessboard[i][Math.abs(col-(row-i))] == 1){
return false;
}
}
if(col+(row-i) >= 0 && col+(row-i)<8){
if( chessboard[i][Math.abs(col+(row-i))] == 1 ){
return false;
}
}
}
return true;
}
public static void main(String[] args) {
Queue8 queue8 = new Queue8();
System.out.println("原棋盘:");
queue8.printChessboard();
queue8.calculateLocation(0);
}
}
计算的结构是共有92种摆法