【发布时间】:2023-03-26 05:50:01
【问题描述】:
所以我有一个程序可以正确解决迷宫问题,并将解决方案存储在一个多维整数数组solvedMaze 中,如下所示:
110111
110101
010100
110100
011100
000000
指出起点和终点在哪里:
S10111
11010E
010100
110100
011100
000000
我必须解决和回溯迷宫路径的代码如下:
public List<Location> solution() {
int[][] solvedMaze = new int[height][width];
Location current;
PriorityQueue<Location> queue = new PriorityQueue<>(new Comparator<Location>() {
@Override
public int compare(Location a, Location b) {
double distanceA = distance(start, a) / 1.5 + distance(a, end);
double distanceB = distance(start, b) / 1.5 + distance(b, end);
return Double.compare(distanceA, distanceB);
}
private double distance(Location first, Location second) {
return Math.abs(first.i() - second.i()) + Math.abs(first.j() - second.j());
}
});
queue.add(start);
while ((current = queue.poll()) != null) {
if (solvedMaze[current.i()][current.j()] != 0) {
continue;
}
int mod = 1;
for (Location next : new Location[]{
current.south(), current.west(), current.north(), current.east()
}) {
if (isInMaze(next) && isClear(next)) {
if (solvedMaze[next.i()][next.j()] == 0) {
queue.add(next);
} else {
mod = Math.min(solvedMaze[next.i()][next.j()], mod);
}
}
}
solvedMaze[current.i()][current.j()] = mod;
if (isFinal(current)) {
break;
}
}
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
System.out.print(solvedMaze[i][j]);
}
System.out.println();
}
if (solvedMaze[end.i()][end.j()] != 0) {
List<Location> route = new ArrayList<>();
Location temp = end;
while (!temp.equals(start)) {
route.add(temp);
Location best = null;
int bestNumber = solvedMaze[temp.i()][temp.j()];
for (Location next : new Location[]{
temp.north(), temp.south(), temp.west(), temp.east()
}) {
if (isInMaze(next) && solvedMaze[next.i()][next.j()] != 0) {
if (solvedMaze[next.i()][next.j()] < bestNumber) {
bestNumber = solvedMaze[next.i()][next.j()];
best = next;
}
}
}
assert best != null;
temp = best;
}
route.add(start);
Collections.reverse(route);
return route;
} else {
return null;
}
}
其中Location 是一个包含x 和y 坐标的类,start 和end 是位置。出于某种原因,我的输出总是null,我不知道为什么。经过一些简单的print 调试后,我发现回溯逻辑中的solvedMaze[next.i()][next.j()] < bestNumber 条件从未进入。方法有什么问题?有没有更好(更有效)的方法来解决它?
【问题讨论】: