public class Queen {
int max=8;
int[] array=new int[max];
public static void main(String[] args) {
Queen queen=new Queen();
queen.name(0);
}
private void name(int index) {
//开始排皇后
if(index==max) {
System.out.println("解法:");
show();
return;
}
for (int i = 0; i < array.length; i++) {
array[index]=i;
if(judge(index)) {
name(index+1);
}
}
}
private boolean judge(int index) {
for (int i = 0; i < index; i++) {
if (array[i]==array[index]||Math.abs(array[index]-array[i])==Math.abs(index-i)) {
return false;
}
}
return true;
}
private void show() {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]+"\t");
}
for (int i = 0; i < array.length; i++) {
}
System.out.println("\n");
}
一维数组实现8皇后问题代码
最新推荐文章于 2024-11-15 18:38:47 发布