2025-01-15 八皇后问题
This commit is contained in:
parent
c1acab5c81
commit
48746fa165
60
src/dataANDcalc/java/Recursion/EigthQueen.java
Normal file
60
src/dataANDcalc/java/Recursion/EigthQueen.java
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
package Recursion;
|
||||||
|
|
||||||
|
public class EigthQueen {
|
||||||
|
|
||||||
|
private int[] chessArr = new int[8];
|
||||||
|
|
||||||
|
private int answer = 0;
|
||||||
|
|
||||||
|
private void chess(int x){
|
||||||
|
// 第八个皇后也已经放好了
|
||||||
|
if (x == 8){
|
||||||
|
answer ++;
|
||||||
|
System.out.println("得到一种解法");
|
||||||
|
show();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
//将第x+1个皇后尝试遍历放到所有列上
|
||||||
|
for (int i = 0; i < 8; i++) {
|
||||||
|
chessArr[x] = i;
|
||||||
|
// 1.判断当前位置是否没有攻击到其他皇后
|
||||||
|
if (isAttack(x)){
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// 2.如果没有攻击到其他皇后,就放下一个皇后
|
||||||
|
chess(x + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// chessArr={0}
|
||||||
|
private boolean isAttack(int x){
|
||||||
|
for (int i = 0; i < x; i++) {
|
||||||
|
// 1.判断当前列是否有皇后
|
||||||
|
if(chessArr[i] == chessArr[x]){
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
// 2.判断斜线是否有皇后
|
||||||
|
if(Math.abs(x - i) == Math.abs(chessArr[x] - chessArr[i])){
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void show(){
|
||||||
|
for (int i = 0; i < 8; i++) {
|
||||||
|
System.out.print(chessArr[i] + " ");
|
||||||
|
}
|
||||||
|
System.out.println();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
EigthQueen eigthQueen = new EigthQueen();
|
||||||
|
eigthQueen.chess(0);
|
||||||
|
int num = eigthQueen.answer;
|
||||||
|
System.out.println("总共获得的解:" + num);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user