八皇后问题:
package tests;
import java.util.LinkedList;
import tests.Ok.Location;
public class EightQuee {
/*
* 知识点:
* 1.深搜思想,每次从x+1行、0列开始深搜,先保证行不重复,然后判断列;
* 2.LinkedList<Location>list=new LinkedList<>();
* 3.生成一个LinkedList类、Location类型对象;
* 4.list.offer()、list.add()都是往里加一个元素;
* 5.list.pollLast(),删除末位元素;
* 6.可以模拟队列,先进先出;
*/
private static final int SIZE = 8; // 皇后的个数,此处设为8,表示8个皇后
private static int count = 0; // 记录摆放的方式数
public static void main(String[] args) {
LinkedList<Location> list = new LinkedList<>();
EightQuees(list, 0, 0);// 0列0行;
System.out.println("八皇后共有"+count+"种摆放方式");
}
public static void EightQuees(LinkedList<Location> list, int x, int y) {
if (list.size() == SIZE) {
printQueen(list);
return;
}
for (int i = y; i <SIZE; i++) {
Location loc = new Location(x, i);
if (isLegal(list, loc)) {
list.add(loc);
EightQuees(list, x+1, 0);//继续从0列开始;
list.pollLast();
}
}
}
private static boolean isLegal(LinkedList<Location> list, Location loc) {
for (Location each : list) {
if (loc.x == each.x || loc.y == each.y) // 判断是否在同一行或同一列
return false;
else if (Math.abs(loc.x - each.x) == Math.abs(loc.y - each.y)) // 判断是否在同一对角线或反对角线上
return false;
}
return true;
}
public static void printQueen(LinkedList<Location> list) {
++count;
for (Location each : list) {
System.out.print(each.toString());
}
System.out.println();
}
public static class Location {
int x;
int y;
public Location(int x, int y) {
this.x = x;
this.y = y;
}
public Location() {
x = 0;
y = 0;
}
public String toString() {
return "(" + x + "," + y + ") ";
}
}
}