【发布时间】:2021-01-06 14:20:54
【问题描述】:
我目前正在研究一个小迷宫求解器项目,您可以在其中找到迷宫中的最短路径,以便更好地理解路径搜索算法,例如本例中的广度优先搜索算法。我的实现使用布尔访问矩阵来标记已访问的单元格以避免重复步骤,然后按以下步骤工作。
第 1 步 - 使用访问队列来保存相邻的单元格。
第 2 步 - 删除队列前面的单元格并将其添加到访问列表中,增加步骤变量。
第 3 步 - 检查相邻的单元格,如果它们不是墙壁并且没有被访问,它们将被添加到访问队列中。
第 4 步 - 重复第 2 步和第 3 步,直到整个队列为空。
广度优先搜索实现有效,它将路径(即 0 秒)转换为访问路径(即 2 秒),但我遇到的问题是我无法将其减少到目标的距离(变量)并变死结束路径返回 0,以便它只显示最短路径和到达它所需的最短步骤?也许一些新的眼睛会看到我错过了什么。提前致谢!
BFS 迷宫求解器实现
import java.util.LinkedList;
import java.util.Queue;
public class BFS {
private static int distance = 0;
// Solves given maze iteratively, input starting position in maze and size of the maze.
public static boolean solve(int[][] maze, int x, int y, int sizeX, int sizeY) {
boolean[][] visited = new boolean[sizeX][sizeY];
Queue<Point> vQueue = new LinkedList<Point>();
vQueue.add(new Point(x, y, null));
while (!vQueue.isEmpty()) {
distance++;
Point p = vQueue.remove();
visited[p.x][p.y] = true;
// 3 is the cell the algorithm is supposed to find.
if (maze[p.x][p.y] == 3) {
maze[p.x][p.y] = 2;
System.out.println("Shortest path has "+ distance + " steps.");
return true;
}
maze[p.x][p.y] = 2;
// Down.
if (visited[p.x-1][p.y] == false && (maze[p.x-1][p.y] == 0 || maze[p.x-1][p.y] == 3)) {
Point nextPoint = new Point(p.x-1, p.y, p);
vQueue.add(nextPoint);
}
// Up.
if (visited[p.x+1][p.y] == false && (maze[p.x+1][p.y] == 0 || maze[p.x+1][p.y] == 3)) {
Point nextPoint = new Point(p.x+1, p.y, p);
vQueue.add(nextPoint);
}
// Right.
if (visited[p.x][p.y+1] == false && (maze[p.x][p.y+1] == 0 || maze[p.x][p.y+1] == 3)) {
Point nextPoint = new Point(p.x, p.y+1, p);
vQueue.add(nextPoint);
}
// Left.
if (visited[p.x][y-1] == false && (maze[p.x][p.y-1] == 0 || maze[p.x][p.y-1] == 3)) {
Point nextPoint = new Point(p.x, p.y-1, p);
vQueue.add(nextPoint);
}
}
return false;
}
// Node class that holds current position and visitation list.
private static class Point{
int x;
int y;
Point parent;
public Point(int x, int y, Point parent) {
this.x = x;
this.y = y;
this.parent = parent;
}
}
}
测试迷宫
public class TestMazeDFS {
private static int[][] maze = {
{1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 1, 0, 1, 1, 1, 1, 1},
{1, 0, 1, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 0, 1, 0, 1},
{1, 0, 0, 0, 1, 0, 1, 0, 1},
{1, 0, 1, 1, 1, 1, 1, 0, 1},
{1, 0, 0, 0, 0, 0, 0 ,3, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1},
};
public int[][] getMaze(){
return this.maze;
}
// prints the maze.
public static void printMaze() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
// if (maze[i][j] == 1) {
// System.out.print('#');
// } else {
// System.out.print(' ');
// }
System.out.print(maze[i][j]);
}
System.out.println();
}
System.out.println();
}
public static void main(String[] args) {
TestMazeDFS maze = new TestMazeDFS();
boolean test = BFS.solve(maze.getMaze(), 1, 1, 9, 9);
System.out.println(test);
printMaze();
}
}
【问题讨论】:
-
将你的方法与@fishinear 结合起来,我就让它工作了!非常感谢!
标签: java algorithm loops breadth-first-search maze