问题描述
我正在尝试为具有以下规则的迷宫编写使用回溯的最短路径算法;
- 可通行的门用 0 表示
- 无法通过的门用 1 表示
- 如果最多只有 1 面墙被破坏,就会有一条路径
- 总有一条路
- 开始在 (0,0) 结束在 (迷宫宽度 - 1,迷宫高度 - 1)
我在下面编写的算法适用于 90% 的情况,但在某些情况下,如果我向左或向上转弯它会失败似乎向左或向上转弯提供了比单独向下和向右转弯更短的路径迷宫里面也很混乱。如果我注释掉 Left 或 Up,那么这些情况也会成功,但其他情况会失败。我做错了什么?
public class ShortestPath {
public static int shortestPath(int[][] map) {
if (map == null || map.length == 0 || map[0].length == 0) {
return 0;
}
int[][] visitedMap = new int[map.length][map[0].length];
return findShortestPath(map,visitedMap,map[0].length - 1,map.length - 1,Integer.MAX_VALUE,1,0);
}
private static boolean canVisit(int[][] map,int[][] visitedMap,int x,int y) {
return (!isWall(map,x,y) && !hasVisited(visitedMap,y));
}
private static boolean isWall(int[][] map,int y) {
return map[y][x] == 1;
}
private static boolean hasVisited(int[][] visitedMap,int y) {
return visitedMap[y][x] == 1;
}
private static boolean isValid(int[][] map,int y) {
return (y < map.length && x < map[0].length && x >= 0 && y >= 0);
}
private static boolean hasPath(int[][] map,int y) {
boolean hasPath = (
(isValid(map,x - 1,y) && !isWall(map,y)) ||
(isValid(map,y - 1) && !isWall(map,y - 1) && !hasVisited(visitedMap,y - 1)) ||
(isValid(map,y + 1) && !isWall(map,y + 1) && !hasVisited(visitedMap,y + 1)) ||
(isValid(map,x + 1,y)));
return hasPath;
}
private static int findShortestPath(int[][] map,int x1,int y1,int x2,int y2,int minimumdist,int dist,int brokenWallCount) {
if (x1 == x2 && y1 == y2) {
return (int) Math.min(minimumdist,dist);
}
visitedMap[y1][x1] = 1;
int nextX = 0;
int nextY = 0;
nextX = x1 - 1;
nextY = y1;
// Left 4 Fails
if (isValid(map,nextX,nextY)) {
if (canVisit(map,nextY)) {
minimumdist = findShortestPath(map,nextY,x2,y2,minimumdist,dist + 1,brokenWallCount);
} else if (isWall(map,nextY)) {
if (brokenWallCount < 1 && hasPath(map,nextY)) {
minimumdist = findShortestPath(map,brokenWallCount + 1);
}
}
}
nextX = x1 + 1;
nextY = y1;
// Right
if (isValid(map,brokenWallCount + 1);
}
}
}
nextX = x1;
nextY = y1 - 1;
// Up 5 Fails
if (isValid(map,brokenWallCount + 1);
}
}
}
nextX = x1;
nextY = y1 + 1;
// Down
if (isValid(map,brokenWallCount + 1);
}
}
}
visitedMap[y1][x1] = 0;
return minimumdist;
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)