java-解决滑动拼图难题时的A *算法执行时间很长

尝试运行24个Tile拼图及以上版本的代码时,代码执行时间很长(大于3分钟)(对于8 Tile Puzzle而言,运行速度非常快).该代码可以在下面找到.

while (openQueue.isEmpty() == false) {
    State queueHead = openQueue.remove();
    openMap.remove(queueHead.hashCode());
    closedMap.put(queueHead.hashCode(), queueHead);
    State queueHeadState = queueHead;

    if (Constants.debug) {
        System.out.println("Popped State");
        HeuristicSolverUtility.printState(queueHead);   
    }
    // If reached goal state . Termination condition.
    if (queueHead.equals(goalState)) {
        break;
    } else {
        List<Action> listOfPossibleActions = queueHeadState
                .getPossibleActions();
        Iterator<Action> actIter = listOfPossibleActions.iterator();
        while (actIter.hasNext()) {
            // Here it performs Tile UP, DOWN, LEFT and RIGHT operations 
            Action actionOnState = actIter.next();
            StateP newState = actionOnState.applyTo(queueHeadState);
            newState.setHeuristicCost((double) ManhattanDistance
                    .calculate(newState));
            newState.setParent(queueHead);
            newState.setAction(actionOnState);

            if (!closedMap.containsKey(newState.hashCode()) && !openMap.containsKey(newState.hashCode())) {
                openQueue.offer(newState);
                openMap.put(newState.hashCode(), newState);
            } else if (openMap.containsKey(newState.hashCode())) {
                System.out.println("State found in Open Map");
                State stateFetchedFromOpenMap = openMap.get(newState.hashCode());
                if (stateFetchedFromOpenMap.getPathCost() > newState.getPathCost()) {
                    openMap.remove(stateFetchedFromOpenMap.hashCode());
                    openMap.put(newState.hashCode(), newState);
                    openQueue.remove(stateFetchedFromOpenMap);
                    openQueue.add(newState);
                }
            }
        }
    }
}

这是我的哈希码:

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

这是优先级队列比较器的代码:-

public static class HeuristicComparator implements Comparator<State> {
    public int compare(State o1, State o2) {
        Double result;

        result = o1.getKey() - o2.getKey();
        if (result == 0.0) {
            // Ties among minimal f values are resolved in favor of the
            // deepest node in the search tree
            // i.e. the closest node to the goal
            result = (double) (o2.getPathCost() - o1.getPathCost());
        }
        if (result > 0.0) {
            return 1;
        }
        return -1;
    }
}

我不确定为什么我的A *实现要花这么长时间才能计算出24个拼板拼图及以上版本.如何优化代码以更快地进行计算,是否还有任何导致其花费这么长时间的错误?

如果您对整个代码感兴趣,可以找到here

解决方法:

正如Turing85所提到的,这是一个NP完全问题,因此您不太可能拥有快速的运行时间.

我建议您可以执行以下操作:

>尝试使用different heuristic
>尝试使用bidirectional search

上一篇:在非本地时区中快速解析Python日期时间,以节省夏令时


下一篇:python-使Numpy.where在遇到第一个true之后停止