gpt4 book ai didi

java - A* 算法在解决 Sliding Tile 难题时执行了很长时间

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:42:56 25 4
gpt4 key购买 nike

在尝试运行 24 block 及以上拼图的代码时,代码执行了很长时间(超过 3 分钟)(对于 8 block 拼图运行得非常快)。代码可以在下面找到。

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 block 及以上的拼图。我如何优化我的代码以加快计算速度,是否存在导致它花费这么长时间的错误?

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

最佳答案

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

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

  1. 尝试使用different heuristic
  2. 尝试使用bidirectional search

关于java - A* 算法在解决 Sliding Tile 难题时执行了很长时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31097669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com