八皇后问题也是堆栈的典型应用场景,里面也涉及递归的使用,简单来说就是皇后棋子可以吃掉横竖方向和对角斜方向的其它皇后棋子,棋盘是8X8大小且下八个棋子的就是八皇后(以此类推)
解题思路就是可以每一行(或每一列)依次放一个棋子,之后在下一行(或下一列)再放棋子的时候需要比较之前已经放了的棋子是否会有冲突(被其他皇后攻击),依次放棋子直至完成八个棋子的存放就是一种解决方案。
上代码,我这里是按照行的顺序依次放棋子的
public class EightQueen {
public static int TRUE=1, FALSE=0,EIGHT=8;
public static int[] queen = new int[EIGHT]; //存放八个皇后的列位置
public static int number = 0;
public EightQueen() {
number = 0;
}
//按enter函数
public static void PressEnter() {
char tChar;
System.out.println();
System.out.println();
System.out.println("...按下enter键继续...");
try {
tChar = (char)System.in.read();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void decide_position(int value) {
int i = 0;
while( i < EIGHT ) {
//是否收到攻击判断
if( attack(i, value) != 1 ) {
queen[value] = i;
if(value == 7) {
print_table();
}
else {
decide_position(value + 1);
}
}
i++;
}
}
public static int attack(int row, int col) {
int i=0,atk=FALSE;
int offset_row=0, offset_col=0;
while (atk!=1 && i<col) {
offset_col = Math.abs(i-col);
offset_row = Math.abs(queen[i] - row);
if(queen[i] == row || offset_row==offset_col) {
atk = TRUE;
}
i++;
}
return atk;
}
public static void print_table() {
int x=0, y=0;
number+=1;
System.out.println();
for(x=0;x<EIGHT;x++) {
for (y=0;y<EIGHT;y++) {
if(x == queen[y]) {
System.out.print("<*>");
}
else {
System.out.print("<->");
}
}
System.out.println();
}
PressEnter();
}
public static void main(String[] args) {
EightQueen.decide_position(0);
}
}
运行结果: