递归解决八皇后的问题,列出所有八皇后的可能
package com.recursion;
import java.util.Arrays;
/**
* 递归解决八皇后的问题
* @author Administrator
*
*/
public class Empress {
// 初始化八皇后的位置
private static int[] graph = new int [8];
private static int max = 8;
public static void main(String[] args) {
check(0);
}
public static void check(int n) {
if(n == max) {
print();
return;
}
for (int i = 0; i < graph.length; i++) {
graph[n] = i;
if(isExist(n)) {
check(n+1);
}
}
}
private static void print() {
System.out.println(Arrays.toString(graph));
}
/**
* 是否可放置
* @param n
* @return true 可以 false 不行
*/
public static boolean isExist(int n) {
boolean isExist = true;
for (int i = 0; i < n; i++) {
if(graph[n] ==graph[i] || Math.abs(n-i) == Math.abs(graph[n] - graph[i])) {
return false;
}
}
return isExist;
}
public static void printGraph(String[][] graph) {
for (String[] strings : graph) {
Arrays.stream(strings).forEach((x)-> System.out.print(x+" "));
System.out.println();
}
}
public static String[][] createGraph(int x, int y) {
String[][] graph = new String[x][y];
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
graph[i][j] = "口";
}
}
return graph;
}
}
注意:代码还未经过测试,借鉴时请注意, 抄的韩顺平老师的数据结构分析