您的位置:首页 > 编程语言 > Java开发

八皇后--java实现

2016-09-10 23:07 134 查看
import com.google.common.collect.Sets;

import java.util.Set;
import java.util.Stack;

/**
* Class description  八皇后
* Created with IntelliJ IDEA
* User :zww.zhang
* Date:2016/9/10
*/
public class FindPath {

private static final int FNAGGE = 8;
public static int count = 0;
private Set<QueuePoint> danger = Sets.newHashSet();

private boolean isDanger(QueuePoint point) {
if (point == null) return false;
int x = point.getRow();
int y = point.getColumn();
for (QueuePoint queuePoint : danger) {
if (queuePoint.getColumn() == y || queuePoint.getRow() == x) {
return true;
}
int tempx = queuePoint.getRow();
int tempy = queuePoint.getColumn();
//左上方
for (int lux = tempx, luy = tempy; lux > 0 && luy > 0; lux--, luy--) {
if (x == lux && y == luy) {
return true;
}
}
//右上方
for (int lux = tempx, luy = tempy; lux > 0 && luy <= 8; lux--, luy++) {
if (x == lux && y == luy) {
return true;
}
}
//右下方
for (int lux = tempx, luy = tempy; lux <= 8 && luy <= 8; lux++, luy++) {
if (x == lux && y == luy) {
return true;
}
}
//左下方
for (int lux = tempx, luy = tempy; lux <= 8 && luy > 0; lux++, luy--) {
if (x == lux && y == luy) {
return true;
}
}
}
return false;
}

private void findPath(int row, QueuePoint son, QueuePoint parent) {
if (row == FNAGGE && !isDanger(son)) {
son.setParent(parent);
printPath(son);
} else if (!isDanger(son)) {
if (son != null) {
joinDanger(son);
son.setParent(parent);
}
row++;
for (int cl = 1; cl <= FNAGGE; cl++) {
findPath(row, new QueuePoint(row, cl), son);
}
remove(son);
}
}

public static void main(String[] args) {
FindPath path = new FindPath();
path.findPath(0, null, null);
}

private void remove(QueuePoint son) {
danger.remove(son);
}

private void joinDanger(QueuePoint son) {
if (son != null) {
danger.add(son);
}
}

private void printPath(QueuePoint son) {
count++;
QueuePoint temp = son;
Stack<String> strings = new Stack<>();

f2ef
while (temp != null) {
StringBuilder rowstr = new StringBuilder();
for (int i = 1; i <= 8; i++) {
if (i == temp.getColumn()) {
rowstr.append(" 1 ");
} else {
rowstr.append(" 0 ");
}
}
strings.push(rowstr.toString());
temp = temp.getParent();
}
while (strings.size() > 0) {
System.out.println(strings.pop());
}
strings = null;
System.out.println("--上图--" + count);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: