Java 八数码问题求解

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 A..
摘要由CSDN通过智能技术生成


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.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值