思路分析
代码实现
package com.monster.digui;
import org.junit.Test;
/**
* @author Monster
* @version v1.0
* @time 03-17-2021 13:50:09
* @description: 八皇后问题
*/
public class Queue {
int max = 8;
int[] queues = new int[max];
int count = 0;
private void check(int n) {
if (n == max) {
count++;
print();
return;
}
for (int i = 0; i < max; i++) {
queues[n] = i;
if (judge(n)) {
check(n + 1);
}
}
}
private boolean judge(int n) {
for (int i = 0; i < n; i++) {
if (queues[n] == queues[i] || Math.abs(queues[n] - queues[i]) == Math.abs(n - i)) {
return false;
}
}
return true;
}
private void print() {
System.out.print("第" + count + "种八皇后排法为:");
for (int queue : queues) {
System.out.print(queue + 1 + " ");
}
System.out.println();
}
@Test
public void test() {
Queue queues = new Queue();
queues.check(0);
}
}