import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
//以0为移动对象 Hn是错位个数/距离目标位置的距离
public class EightPuzzle implements Comparable {
public static void main(String args[]) {
ArrayList<EightPuzzle> open = new ArrayList<EightPuzzle>(); //定义open表
ArrayList<EightPuzzle> close = new ArrayList<EightPuzzle>();
EightPuzzle start = new EightPuzzle();
EightPuzzle target = new EightPuzzle();
int startnum[] = {
2, 1, 6, 4, 0, 8, 7, 5, 3};
int targetnum[] = {
1, 2, 3, 8, 0, 4, 7, 6, 5};
start.setNum(startnum);
target.setNum(targetnum);
long startTime = System.currentTimeMillis(); //获取开始时间
if (start.isSolvable(target)) {
//判断有解之后 起始状态逆序数的奇偶性和目标状态的奇偶性是一样的则有解
start.init(target); //初始化初始状态 Fn Gn Hn
open.add(start);
while (open.isEmpty() == false) {
//open表为空则失败
Collections.sort(open); //按照Fn的值排序--Fn越小越先拓展
EightPuzzle best = open.get(0); //从open表中取出最小估值的状态并移除open表
open.remove(0);
close.add(best);
if (best.isTarget(target)) {
//如果当前状态为目标状态
best.printRoute(); //输出
long end = System.currentTimeMillis(); //获取结束时间
System.out.println("程序运行时间: " + (end - startTime) + "ms");
System.exit(0);
}
int move;
//由best状态进行扩展 并加入到open表中
if (best.isMoveUp()) {
//能向上移动
move = 0;
EightPuzzle up = best.moveUp(move); //返回移动后的状态
up.operation(open, close, best, target);//0的位置上移之后状态不在close和open中 设定best为其父状态
}
if (best.isMoveDown()) {
move = 1;
EightPuzzle up = best.
Java 八数码问题求解
最新推荐文章于 2021-12-15 23:52:56 发布
本文详细介绍了如何使用Java编程解决经典的八数码问题,包括算法思路、关键代码实现及问题求解过程。通过理解位运算和堆栈数据结构,读者可以深入掌握此问题的解决策略。
摘要由CSDN通过智能技术生成