📄 eightqueue.java
字号:
//用回朔搜索法解八皇后
import java.io.*;
public class EightQueue {
String[][] rec = new String[8][8];
int[] a = new int[8];
int[] b = new int[15];
int[] c = new int[15];
int sum;
public EightQueue() {
super();
for (int i = 0; i < this.rec.length; i++) {
for (int j = 0; j < this.rec[i].length; j++) {
this.rec[i][j] = "○";
}
}
}
public void prt() {
System.out.println("");
for (int i = 0; i < this.rec.length; i++) {
for (int j = 0; j < this.rec[i].length; j++) {
System.out.print(this.rec[i][j] + " ");
}
System.out.println("");
}
System.out.println("");
}
/**
* set the queen of line i
*
* @param i
*/
void queue(int i) {
for (int iColumn = 0; iColumn < 8; iColumn++) {
if (a[iColumn] == 0 && b[i - iColumn + 7] == 0&& c[i + iColumn] == 0) {
// do not conflict
rec[i][iColumn] = "●";
a[iColumn] = 1;
b[i - iColumn + 7] = 1;
c[i + iColumn] = 1;
if (i < 7)
queue(i + 1);
else {
prt();
sum++;
}
// whatever how to put the queen, mission is impossible. rollback
rec[i][iColumn] = "○";
a[iColumn] = 0;
b[i - iColumn + 7] = 0;
c[i + iColumn] = 0;
}
}
}
/**
* 8 queen
* @param args
*/
public static void main(String[] args) {
EightQueue eq = new EightQueue();
eq.queue(0);
System.out.println(eq.sum);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -