第一次实验,8皇后问题算法
来源:互联网 发布:apache 负载均衡 策略 编辑:程序博客网 时间:2024/06/06 02:36
public class EightQueen { Queen[] stack = new Queen[8]; int sp = 0; int num = 0; public EightQueen() { num = 8; stack = new Queen[num]; sp = 0; } public EightQueen(int num) { this.num = num; stack = new Queen[num]; sp = 0; } /*打印皇后的坐标列表。*/ public void list() { System.out.println("开始列表中堆栈指针以及8皇后问题的解:"); for (int i = 0; i < sp; i++) { stack[i].pos.println(); } System.out.println("结束列表堆栈指针:"); } /*主算法流程。@Administrator**/ public void calc() { sp = 0; stack[sp++] = new Queen(); while (sp >= 0 && sp <= num - 1) { Queen queen = getQueen(sp); if (null == queen) { boolean flag = true; while (flag) { --sp; if (sp < 0) break; if (stack[sp].pos.y == num - 1) { } else { stack[sp++].pos.y++; flag = false; for (int k = 0; k < sp - 1; k++) { if (stack[k].isUnderControl(stack[sp - 1].pos)) { flag = true; break; } } } } } else { stack[sp++] = queen; } } } public Queen getQueen(int x) { boolean flag = true; int y = 0; while (flag) { flag = false; for (int i = 0; i < x; i++) { if (stack[i].isUnderControl(new Point(x, y))) { flag = true; break; } } if (flag && y <= num - 1) { y++; } else if (y >= num) { return null; } } return new Queen(new Point(x, y)); } public static void main(String[] args) { EightQueen a = new EightQueen(20); a.calc(); if (a.sp > 0) { a.list(); } else { System.out.println("这个问题无解!"); } } } class Point { int x, y; public void println() { System.out.println("指针是 :[x,y]=[" + x + "," + y + "]"); } public Point() { x = 0; y = 0; } public Point(int x, int y) { this.x = x; this.y = y; } /** * @return int */ public int getX() { return x; } /** * @return int */ public int getY() { return y; } /** * 设置 x. * @param x The x to set */ public void setX(int x) { this.x = x; } /** * 设置 y. * @param y The y to set */ public void setY(int y) { this.y = y; } } class Queen { Point pos; public Queen() { pos = new Point(); } public Queen(Point pos) { this.pos = pos; } public boolean isUnderControl(Point point) { boolean ret = true; if (point.x != pos.x && point.y != pos.y && Math.abs(point.x - pos.x) != Math.abs(point.y - pos.y) && Math.abs(point.x + point.y) != Math.abs(pos.x + pos.y)) { ret = false; } return ret; } }
0 0
- 第一次实验,8皇后问题算法
- 第一次实验,八皇后问题
- 第一次实验——八皇后问题
- 第一次实验:NPC,回溯,八皇后问题
- 第一次实验——八皇后问题
- 第一次实验--八皇后及N皇后问题
- 第一次实验:八皇后及N皇后问题
- 第一次实验 八皇后及N皇后问题
- 算法第一次实验 NPC问题
- 8皇后问题算法
- 【算法】8皇后问题
- 8皇后问题算法
- 第一次实验--NPC问题(回溯算法、聚类分析)
- 第一次实验--NPC问题(回溯算法)
- [算法学习]8皇后问题
- 第一次实验--NPC问题(回溯算法、聚类分析)
- 第一次实验作业(NPC问题----回溯算法,聚类分析)
- 第一次实验——NPC问题(回溯算法,聚类分析)
- Swift中UIView类方法(animateWithDuration)的使用
- AVAYA面经:再一次意识到自己的技术有多水
- http://www.gui8.cc/ iCloud框架开发:受益的是所有人
- 堆排序
- 如何计算两个文档的相似度(一)
- 第一次实验,8皇后问题算法
- 关于ScreenToClient
- 可预览的多图片上传(不用刷新页面)
- 获取一个路径所在硬盘驱动器的类型
- 百度语音识别开放平台SDK使用方法
- SQL语句的MINUS,INTERSECT和UNION ALL
- 招回率和正确率
- XForms xpath使用手册
- 使用Nginx反向代理来实现简单的负载均衡