15 Puzzle A* Some cases do not work

Asked

Viewed 39 times

1

I’m trying to implement the A Star algorithm to solve the 15-puzzle problem however there are some that run for infinite time without solving the problem.

for example the input(the top one is the initial one and the bottom one the objective) that should give in the output "56" moves :

2F1C856B49A73ED0
123456789ABCDEF0

Other cases of 56 movements work perfectly but this no

public class AStar {

static class State {
    private Ilayout layout;
    private State father;
    private double g;
    private int h;
    public State(Ilayout l, State n) {
        layout = l;
        father = n;
        if (father!=null){
            g = father.g + l.getG();
            h= l.getH();
        }
        else g = 0.0;
    }
    public String toString() { return layout.toString(); }
    public double getG() {return g;}
    public double getH() {return h;}
}

protected Queue<State> abertos;
@SuppressWarnings("unused")
private List<State> fechados;
private State actual;
private Ilayout objective;

final private List<State> sucessores(State n) {
    List<State> sucs = new ArrayList<>();
    List<Ilayout> children = n.layout.children(objective);

    for(Ilayout e: children) {
        if (n.father == null || !e.equals(n.father.layout)){
            State nn = new State(e, n);
            sucs.add(nn);
        }
    }

    return sucs;
}


final public Iterator<State> solve(Ilayout s, Ilayout goal) {
    objective = goal;
    Queue<State> abertos = new PriorityQueue<>(10,(s1, s2) -> (int) Math.signum((s1.getG()+s1.getH())-(s2.getG()+s2.getH())) );//Queue<Integer> responsta = new PriorityQueue<>(10,(s1, s2) -> (int) Math.signum(s1-s2) );
    List<State> A = new ArrayList<>();
    abertos.add(new State(s, null));
    List<State> sucs;
    Hashtable<String,Integer> a = new Hashtable<String, Integer>();
    a.put(abertos.peek().layout.getBoard(), 0);
    if(abertos.peek().layout.isGoal(objective)  ) {
        A.add(actual);
        return A.listIterator();
    }
    try {
        while (true) {
            if(abertos.isEmpty()) return null;
            actual = abertos.remove();
            a.put(actual.layout.getBoard(), (int) actual.getG());
            if (actual.layout.isGoal(objective)) {
                A.add(actual);
                return A.iterator();
            }
            else {
                if(actual.getG()+actual.getH()<81){
                    sucs = this.sucessores(actual);
                    for (int i = 0; i < sucs.size(); i++) {
                        if (!a.containsKey(sucs.get(i).layout.getBoard())) {
                            abertos.add(sucs.get(i));
                        }
                    }
                }
            }
        }
    }catch(OutOfMemoryError E) {
        return null;
    }
}}
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.