Java 8-谜题解无限执行

Java 8-谜题解无限执行,java,computer-science,artificial-intelligence,Java,Computer Science,Artificial Intelligence,我正在寻找使用a*算法解决问题的方法。我在网上找到了这个项目。请参阅文件-proj1和EightPuzzle。proj1包含程序的入口点(main()函数),EightPuzzle描述了拼图的特定状态。每个州都是8字谜的一个对象0){ EightPuzzle x=openset.peek(); 如果(x.mapEquals(目标)) { 堆栈显示=重建(x); System.out.println(“打印解决方案…”); System.out.println(start.toString());

我正在寻找使用
a*算法解决问题的方法。我在网上找到了这个项目。请参阅文件-
proj1
EightPuzzle
。proj1包含程序的入口点(
main()
函数),EightPuzzle描述了拼图的特定状态。每个州都是8字谜的一个对象<我觉得逻辑上没有错。但它会永远循环我尝试过的这两个输入:
{8,2,7,5,1,6,3,0,4}
{3,1,6,8,4,5,7,2,0}
。它们都是有效的输入状态。代码有什么问题?


注意

  • 为了更好地查看,请将代码复制到记事本++或其他文本中 编辑器(能够识别java源文件) 因为代码中有很多注释
  • 由于*需要启发式,他们提供了使用 曼哈顿距离和计算 放错地方的瓷砖。并确保执行最佳启发式 首先,他们实现了一个
    PriorityQueue
    compareTo()
    函数在
    EightPuzzle
    类中实现
  • 通过更改
    proj1
    类的
    main()
    函数中的
    p1d
    值,可以更改程序的输入
  • 我之所以说上述两个输入存在解决方案,是因为小程序解决了它们。请确保从小程序中的选项中选择8-puzzle。

    EDIT1
    我输入了
    {0,5,7,6,8,1,2,4,3}
    。大约花了
    10秒
    ,结果是26步。但是小程序在
    0.0001秒内以
    24次移动
    给出了一个结果。

    EDIT2
    在调试过程中,我注意到随着节点的扩展,新节点在一段时间后都有一个启发式-
    f\n
    as
    11
    12
    。它们似乎从未减少。因此,经过一段时间后,
    PriorityQueue(openset)
    中的所有状态的启发式值都是11或12。因此,没有太多可供选择的节点,可以扩展到哪个节点。因为最小的是11,最高的是12。这正常吗?

    EDIT3
    这是发生无限循环的代码段(在proj1-astar()中)openset是包含未展开节点的优先队列,closedset是包含展开节点的链接列表。
while(openset.size()>0){

EightPuzzle x=openset.peek();
如果(x.mapEquals(目标))
{
堆栈显示=重建(x);
System.out.println(“打印解决方案…”);
System.out.println(start.toString());
打印(toDisplay);
返回;
}          
closedset.add(openset.poll());
LinkedList邻居=x.getChildren();
while(neighbor.size()>0)
{
EightPuzzle y=邻居。removeFirst();
if(闭合集包含(y)){
继续;
}          
如果(!closedset.包含(y)){
openset.add(y);
}              
}
}



EDIT4

我已经找到了这个无限循环的原因。看看我的答案。但是执行大约需要25-30秒,这是相当长的时间。A*应该比这快得多。小程序在0.003秒内完成此操作我将奖励改善绩效的奖金。


对于快速参考,我已粘贴了两个类,但没有注释:

八尺
import java.util.*;
公共类EightPuzzle实现了可比较的{
int[]拼图=新的int[9];
int h_n=0;
int hueristic_type=0;
int g_n=0;
int f_n=0;
EightPuzzle父项=null;
公共八方(int[]p,int h_类型,int成本)
{
这个谜题=p;
this.hueristic_type=h_type;
this.h_n=(h_type==1)?h1(p):h2(p);
这g_n=成本;
this.f_n=h_n+g_n;
}
公共int getF_n()
{
返回fn;
}
public void setParent(EightPuzzle输入)
{
this.parent=输入;
}
公共EightPuzzle getParent()
{
将此文件返回给父对象;
}
公共整数反转()
{
/*
*定义:对于目标之外的任何其他配置,
*无论何时,当一个数字较大的磁贴位于
*数字较小的瓷砖,这两块瓷砖被称为倒置
*/
int反转=0;
for(int i=0;i                    EightPuzzle x = openset.peek();


                    if(x.mapEquals(goal))
                    {

                             Stack<EightPuzzle> toDisplay = reconstruct(x);
                             System.out.println("Printing solution... ");
                             System.out.println(start.toString());
                             print(toDisplay);
                             return;
                             
                    }          
                    closedset.add(openset.poll());
                    LinkedList <EightPuzzle> neighbor = x.getChildren();              
                    while(neighbor.size() > 0)
                    {
                            EightPuzzle y = neighbor.removeFirst();
                            if(closedset.contains(y)){
                                    continue;
                            }          
                            if(!closedset.contains(y)){
                                    openset.add(y);
                            }              
                    }
               
            }
 import java.util.*;
    
    public class EightPuzzle implements Comparable <Object> {
           
           
            int[] puzzle = new int[9];
            int h_n= 0;
            int hueristic_type = 0;
            int g_n = 0;
            int f_n = 0;
            EightPuzzle parent = null;
    
           
            public EightPuzzle(int[] p, int h_type, int cost)
            {
                    this.puzzle = p;
                    this.hueristic_type = h_type;
                    this.h_n = (h_type == 1) ?  h1(p) : h2(p);
                    this.g_n = cost;
                    this.f_n = h_n + g_n;
            }
            public int getF_n()
            {
                    return f_n;
            }
            public void setParent(EightPuzzle input)
            {
                    this.parent = input;
            }
            public EightPuzzle getParent()
            {
                    return this.parent;
            }
    
            public int inversions()
            {
                    /*
                     * Definition: For any other configuration besides the goal,
                     * whenever a tile with a greater number on it precedes a
                     * tile with a smaller number, the two tiles are said to be inverted
                     */
                    int inversion = 0;
                    for(int i = 0; i < this.puzzle.length; i++ )
                    {
                            for(int j = 0; j < i; j++)
                            {
                                    if(this.puzzle[i] != 0 && this.puzzle[j] != 0)
                                    {
                                    if(this.puzzle[i] < this.puzzle[j])
                                            inversion++;
                                    }
                            }
    
                    }
                    return inversion;
                   
            }
            public int h1(int[] list)
            // h1 = the number of misplaced tiles
            {
                    int gn = 0;
                    for(int i = 0; i < list.length; i++)
                    {
                            if(list[i] != i && list[i] != 0)
                                    gn++;
                    }
                    return gn;
            }
            public LinkedList<EightPuzzle> getChildren()
            {
                    LinkedList<EightPuzzle> children = new LinkedList<EightPuzzle>();
                    int loc = 0;
            int temparray[] = new int[this.puzzle.length];
            EightPuzzle rightP, upP, downP, leftP;
                    while(this.puzzle[loc] != 0)
                    {
                            loc++;
                    }
                    if(loc % 3 == 0){
                            temparray = this.puzzle.clone();
                            temparray[loc] = temparray[loc + 1];
                            temparray[loc + 1] = 0;
                            rightP = new EightPuzzle(temparray, this.hueristic_type, this.g_n + 1);
                            rightP.setParent(this);
                            children.add(rightP);
    
                    }else if(loc % 3 == 1){
                    //add one child swaps with right
                            temparray = this.puzzle.clone();
                            temparray[loc] = temparray[loc + 1];
                            temparray[loc + 1] = 0;
                           
                            rightP = new EightPuzzle(temparray, this.hueristic_type, this.g_n + 1);
                            rightP.setParent(this);
                            children.add(rightP);
                            //add one child swaps with left
                            temparray = this.puzzle.clone();
                            temparray[loc] = temparray[loc - 1];
                            temparray[loc - 1] = 0;
                           
                            leftP = new EightPuzzle(temparray, this.hueristic_type, this.g_n + 1);
                            leftP.setParent(this);
                            children.add(leftP);
                    }else if(loc % 3 == 2){
                    // add one child swaps with left
                            temparray = this.puzzle.clone();
                            temparray[loc] = temparray[loc - 1];
                            temparray[loc - 1] = 0;
                           
                            leftP = new EightPuzzle(temparray, this.hueristic_type, this.g_n + 1);
                            leftP.setParent(this);
                            children.add(leftP);
                    }              
                   
                    if(loc / 3 == 0){
                    //add one child swaps with lower
                            temparray = this.puzzle.clone();
                            temparray[loc] = temparray[loc + 3];
                            temparray[loc + 3] = 0;
                           
                            downP = new EightPuzzle(temparray, this.hueristic_type, this.g_n + 1);
    
                            downP.setParent(this);
    
                            children.add(downP);
                   
                           
                    }else if(loc / 3 == 1 ){
                            //add one child, swap with upper
                            temparray = this.puzzle.clone();
                            temparray[loc] = temparray[loc - 3];
                            temparray[loc - 3] = 0;
                           
                            upP = new EightPuzzle(temparray, this.hueristic_type, this.g_n + 1);
                            upP.setParent(this);
    
                            children.add(upP);
                            //add one child, swap with lower
                            temparray = this.puzzle.clone();
                            temparray[loc] = temparray[loc + 3];
                            temparray[loc + 3] = 0;
                           
                            downP = new EightPuzzle(temparray, this.hueristic_type, this.g_n + 1);
                            downP.setParent(this);
    
                            children.add(downP);
                    }else if (loc / 3 == 2 ){
                            //add one child, swap with upper
                            temparray = this.puzzle.clone();
                            temparray[loc] = temparray[loc - 3];
                            temparray[loc - 3] = 0;
                           
                            upP = new EightPuzzle(temparray, this.hueristic_type, this.g_n + 1);
                            upP.setParent(this);
    
                            children.add(upP);
                    }
    
                    return children;
            }
            public int h2(int[] list)
            // h2 = the sum of the distances of the tiles from their goal positions
            // for each item find its goal position
            // calculate how many positions it needs to move to get into that position
            {
                    int gn = 0;
                    int row = 0;
                    int col = 0;
                    for(int i = 0; i < list.length; i++)
                    {
                            if(list[i] != 0)
                            {
                                    row = list[i] / 3;
                                    col = list[i] % 3;
                                    row = Math.abs(row - (i / 3));
                                    col = Math.abs(col - (i % 3));
                                    gn += row;
                                    gn += col;
                            }
                           
                    }
                    return gn;
            }
    
            public String toString()
            {
                    String x = "";
                    for(int i = 0; i < this.puzzle.length; i++){
                            x += puzzle[i] + " ";
                            if((i + 1) % 3 == 0)
                                    x += "\n";
                    }
                    return x;
            }
            public int compareTo(Object input) {
                   
                   
                    if (this.f_n < ((EightPuzzle) input).getF_n())
                            return -1;
                    else if (this.f_n > ((EightPuzzle) input).getF_n())
                            return 1;
                    return 0;
            }
           
            public boolean equals(EightPuzzle test){
                    if(this.f_n != test.getF_n())
                            return false;
                    for(int i = 0 ; i < this.puzzle.length; i++)
                    {
                            if(this.puzzle[i] != test.puzzle[i])
                                    return false;
                    }
                    return true;
            }
            public boolean mapEquals(EightPuzzle test){
                    for(int i = 0 ; i < this.puzzle.length; i++)
                    {
                            if(this.puzzle[i] != test.puzzle[i])
                                    return false;
                    }
                    return true;
            }
    
    }
import java.util.*;

public class proj1 {

        /**
         * @param args
         */
       
        public static void main(String[] args) {
               
               
                int[] p1d = {1, 4, 2, 3, 0, 5, 6, 7, 8};
                int hueristic = 2;
                EightPuzzle start = new EightPuzzle(p1d, hueristic, 0);
                int[] win = { 0, 1, 2,
                                          3, 4, 5,
                                          6, 7, 8};
                EightPuzzle goal = new EightPuzzle(win, hueristic, 0);
               
                astar(start, goal);

               

        }
       
        public static void astar(EightPuzzle start, EightPuzzle goal)
        {
                if(start.inversions() % 2 == 1)
                {
                        System.out.println("Unsolvable");
                        return;
                }
//              function A*(start,goal)
//           closedset := the empty set                 // The set of nodes already evaluated.
                LinkedList<EightPuzzle> closedset = new LinkedList<EightPuzzle>();
//           openset := set containing the initial node // The set of tentative nodes to be evaluated. priority queue
                PriorityQueue<EightPuzzle> openset = new PriorityQueue<EightPuzzle>();

                openset.add(start);
               

                while(openset.size() > 0){
//               x := the node in openset having the lowest f_score[] value
                        EightPuzzle x = openset.peek();

//               if x = goal
                        if(x.mapEquals(goal))
                        {
//                   return reconstruct_path(came_from, came_from[goal])
                                 Stack<EightPuzzle> toDisplay = reconstruct(x);
                                 System.out.println("Printing solution... ");
                                 System.out.println(start.toString());
                                 print(toDisplay);
                                 return;
                                 
                        }
//               remove x from openset
//               add x to closedset
                        closedset.add(openset.poll());
                        LinkedList <EightPuzzle> neighbor = x.getChildren();
//               foreach y in neighbor_nodes(x)                
                        while(neighbor.size() > 0)
                        {
                                EightPuzzle y = neighbor.removeFirst();
//                   if y in closedset
                                if(closedset.contains(y)){
//                       continue
                                        continue;
                                }
//                   tentative_g_score := g_score[x] + dist_between(x,y)
//      
//                   if y not in openset
                                if(!closedset.contains(y)){
//                       add y to openset
                                        openset.add(y);
//                      
                                }
//                 
                        }
//               
                }
        }

        public static void print(Stack<EightPuzzle> x)
        {
                while(!x.isEmpty())
                {
                        EightPuzzle temp = x.pop();
                        System.out.println(temp.toString());
                }
        }

        public static Stack<EightPuzzle> reconstruct(EightPuzzle winner)
        {
                Stack<EightPuzzle> correctOutput = new Stack<EightPuzzle>();
               
                while(winner.getParent() != null)
                {
                correctOutput.add(winner);
                winner = winner.getParent();
                }

                return correctOutput;
        }
       
        }
   
if(!closedset.contains(y))
public boolean equals(EightPuzzle test){

                if(this.f_n != ((EightPuzzle)test).getF_n())
                       return false;
            //System.out.println("in equals");
                for(int i = 0 ; i < this.puzzle.length; i++)
                {
                        if(this.puzzle[i] != ((EightPuzzle)test).puzzle[i])
                                return false;
                }
                return true;
        }
 public boolean equals(Object test). 
package eightpuzzle;

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.PriorityQueue;

public class EightPuzzle {

    // Tiles for successfully completed puzzle.
    static final byte [] goalTiles = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };

    // A* priority queue.
    final PriorityQueue <State> queue = new PriorityQueue<State>(100, new Comparator<State>() {
        @Override
        public int compare(State a, State b) { 
            return a.priority() - b.priority();
        }
    });

    // The closed state set.
    final HashSet <State> closed = new HashSet <State>();

    // State of the puzzle including its priority and chain to start state.
    class State {
        final byte [] tiles;    // Tiles left to right, top to bottom.
        final int spaceIndex;   // Index of space (zero) in tiles  
        final int g;            // Number of moves from start.
        final int h;            // Heuristic value (difference from goal)
        final State prev;       // Previous state in solution chain.

        // A* priority function (often called F in books).
        int priority() {
            return g + h;
        }

        // Build a start state.
        State(byte [] initial) {
            tiles = initial;
            spaceIndex = index(tiles, 0);
            g = 0;
            h = heuristic(tiles);
            prev = null;
        }

        // Build a successor to prev by sliding tile from given index.
        State(State prev, int slideFromIndex) {
            tiles = Arrays.copyOf(prev.tiles, prev.tiles.length);
            tiles[prev.spaceIndex] = tiles[slideFromIndex];
            tiles[slideFromIndex] = 0;
            spaceIndex = slideFromIndex;
            g = prev.g + 1;
            h = heuristic(tiles);
            this.prev = prev;
        }

        // Return true iif this is the goal state.
        boolean isGoal() {
            return Arrays.equals(tiles, goalTiles);
        }

        // Successor states due to south, north, west, and east moves.
        State moveS() { return spaceIndex > 2 ? new State(this, spaceIndex - 3) : null; }       
        State moveN() { return spaceIndex < 6 ? new State(this, spaceIndex + 3) : null; }       
        State moveE() { return spaceIndex % 3 > 0 ? new State(this, spaceIndex - 1) : null; }       
        State moveW() { return spaceIndex % 3 < 2 ? new State(this, spaceIndex + 1) : null; }

        // Print this state.
        void print() {
            System.out.println("p = " + priority() + " = g+h = " + g + "+" + h);
            for (int i = 0; i < 9; i += 3)
                System.out.println(tiles[i] + " " + tiles[i+1] + " " + tiles[i+2]);
        }

        // Print the solution chain with start state first.
        void printAll() {
            if (prev != null) prev.printAll();
            System.out.println();
            print();
        }

        @Override
        public boolean equals(Object obj) {
            if (obj instanceof State) {
                State other = (State)obj;
                return Arrays.equals(tiles, other.tiles);
            }
            return false;
        }

        @Override
        public int hashCode() {
            return Arrays.hashCode(tiles);
        }
    }

    // Add a valid (non-null and not closed) successor to the A* queue.
    void addSuccessor(State successor) {
        if (successor != null && !closed.contains(successor)) 
            queue.add(successor);
    }

    // Run the solver.
    void solve(byte [] initial) {

        queue.clear();
        closed.clear();

        // Click the stopwatch.
        long start = System.currentTimeMillis();

        // Add initial state to queue.
        queue.add(new State(initial));

        while (!queue.isEmpty()) {

            // Get the lowest priority state.
            State state = queue.poll();

            // If it's the goal, we're done.
            if (state.isGoal()) {
                long elapsed = System.currentTimeMillis() - start;
                state.printAll();
                System.out.println("elapsed (ms) = " + elapsed);
                return;
            }

            // Make sure we don't revisit this state.
            closed.add(state);

            // Add successors to the queue.
            addSuccessor(state.moveS());
            addSuccessor(state.moveN());
            addSuccessor(state.moveW());
            addSuccessor(state.moveE());
        }
    }

    // Return the index of val in given byte array or -1 if none found.
    static int index(byte [] a, int val) {
        for (int i = 0; i < a.length; i++)
            if (a[i] == val) return i;
        return -1;
    }

    // Return the Manhatten distance between tiles with indices a and b.
    static int manhattanDistance(int a, int b) {
        return Math.abs(a / 3 - b / 3) + Math.abs(a % 3 - b % 3);
    }

    // For our A* heuristic, we just use max of Manhatten distances of all tiles.
    static int heuristic(byte [] tiles) {
        int h = 0;
        for (int i = 0; i < tiles.length; i++)
            if (tiles[i] != 0)
                h = Math.max(h, manhattanDistance(i, tiles[i]));
        return h;
    }

    public static void main(String[] args) {

        // This is a harder puzzle than the SO example
        byte [] initial = { 8, 0, 6, 5, 4, 7, 2, 3, 1 };

        // This is taken from the SO example.
        //byte [] initial = { 1, 4, 2, 3, 0, 5, 6, 7, 8 };

        new EightPuzzle().solve(initial);
    }
}