我正在研究一种在六边形网格中找到路径的算法。为此,我使用深度为3的深度优先搜索。它在找到正确路径的意义上起作用。唯一的问题是它不会返回它。而是返回一个空集。
public Set findPath(Game game, Point origin, Point destination, Set<Point> hasVisited, int depth) throws Exception {
if (origin.equals(destination)){
System.out.println("Return from goal requirements: " + hasVisited);
return hasVisited;
}
if (!origin.equals(destination)){
if (depth != 0) {
for (Point emptyNeighbor : getEmptyNeighbors(game, origin)) {
if (!hasVisited.contains(emptyNeighbor)) {
if (!game.isHiveBrokenAfterPush(origin, emptyNeighbor)) {
hasVisited.add(emptyNeighbor);
game.push(origin.x, origin.y, emptyNeighbor.x, emptyNeighbor.y);
findPath(game, emptyNeighbor, destination, actualOrigin, hasVisited, depth - 1);
hasVisited.remove(emptyNeighbor);
game.push(emptyNeighbor.x, emptyNeighbor.y, origin.x, origin.y);
}
}
}
}
}
System.out.println("Return from end of function: " + hasVisited);
return hasVisited;
}
加载If语句后,它将节点添加到hasVisited并将块推向该方向。然后,它调用自身以继续在树的分支上。它删除hasVisited节点形式,如果无法解决,则取消推送。
现在发生的事情是,最终的回报似乎来自该函数的和。这些是它打印的最后几行:
Return from goal requirements: [java.awt.Point[x=-1,y=0], java.awt.Point[x=-2,y=1], java.awt.Point[x=-2,y=2]]
Return from end of function: [java.awt.Point[x=-1,y=0], java.awt.Point[x=-2,y=1]]
Return from end of function: [java.awt.Point[x=-1,y=0]]
Return from end of function: []
[]
上一组坐标应该返回。但您会看到它返回一个空集。
我试图返回findPath而不是仅仅执行它。这样做只会做一个分支。它不会取消无效的动作。我在代码中看不到问题,希望大家能帮帮我。干杯!
如果只有一种解决方案,请立即返回。递归将一个元素添加到集合中,递归调用并撤消添加。这将改变设置,即结果。当收集多个结果时,将复制该结果。
public boolean findPath(Game game, Point origin, Point destination, Set<Point> hasVisited,
int depth) throws Exception {
if (origin.equals(destination)){
System.out.println("Return from goal requirements: " + hasVisited);
return true;
}
if (depth != 0) {
for (Point emptyNeighbor : getEmptyNeighbors(game, origin)) {
if (!hasVisited.contains(emptyNeighbor)) {
if (!game.isHiveBrokenAfterPush(origin, emptyNeighbor)) {
hasVisited.add(emptyNeighbor);
game.push(origin.x, origin.y, emptyNeighbor.x, emptyNeighbor.y);
boolean found = findPath(game, emptyNeighbor,
destination, actualOrigin, hasVisited, depth - 1);
if (found) {
return true;
}
hasVisited.remove(emptyNeighbor);
game.push(emptyNeighbor.x, emptyNeighbor.y, origin.x, origin.y);
}
}
}
}
System.out.println("Not found");
return false;
}