public class Queen1 {
private int[] column;
private int[] rTol;//右上至左下是否有皇后
private int[] lTor;//左上至右下是否有皇后
private int[] queen;//解答
private int num;//解答的编号
public Queen1() {
column = new int[8+1];
rTol = new int[2*8+1];
lTor = new int[2*8+1];
for(int i=1;i<=8;i++)
column[i] = 1;
for(int i=1;i<=2*8;i++)
rTol[i] = lTor[i] = 1;
queen = new int[8+1];
}
public void backTrack(int i) {
if(i>8) {
showAnswer();
} else {
for(int j=1;j<=8;j++) {
if(column[j] == 1 && rTol[i+j] ==1 && lTor[i-j+8] == 1) {
queen[i] = j;//设定为占用
column[j] = rTol[i+j] = lTor[i-j+8] = 0;
backTrack(i+1);
column[j] = rTol[i+j] = lTor[i-j+8] = 1;
}
}
}
}
protected void showAnswer() {
num ++;
System.out.println("\n解答" + num);
for(int y=1;y<=8;y++) {
for(int x = 1;x<=8;x++) {
if(queen[y] == x) {
System.out.print(" Q");
}else {
System.out.print(" X");
}
}
System.out.println();
}
}
public static void main(String [] args) {
Queen1 queen = new Queen1();
queen.backTrack(1);
}
}
第一次实验——八皇后问题
最新推荐文章于 2023-05-29 12:37:31 发布