八皇后--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); } }
相关文章推荐
- 回溯法求解N皇后问题(Java实现)
- N皇后问题java实现
- 8皇后以及N皇后算法探究,回溯算法的JAVA实现,非递归,循环控制及其优化
- java分治算法实现n皇后问题
- 回溯法求解N皇后问题(Java实现)
- n皇后问题(人工智能试验java实现)
- java分治算法实现n皇后问题
- 8皇后以及N皇后算法探究,回溯算法的JAVA实现,递归方案
- n皇后问题回溯法---java图形界面实现回溯过程
- java分治算法实现n皇后问题
- java实现N皇后问题
- java实现N皇后递归算法
- java实现N皇后迭代算法
- 8皇后以及N皇后算法探究,回溯算法的JAVA实现,非递归,数据结构“栈”实现
- java实现八皇后的排列问题
- n皇后问题java递归实现
- 四皇后问题的代码实现(java)
- java数组实现N皇后问题
- java实现皇后问题
- java分治算法实现n皇后问题