因此,我正在研究一种BFS算法,以在2D二进制迷宫中找到最短路径,并以坐标形式打印该路径。代码正在运行,但是某个地方肯定有一些错误。
基本上,迷宫坐标具有true或false值(其中墙为false)。迷宫中的坐标以称为Pos
的自定义类的形式给出。
我的目标是找到路径,将点添加到列表中(以Pos的形式)并返回数组列表ArrayList<Pos> path
这是我到目前为止所得到的:
import java.util.ArrayList;
import java.util.ArrayDeque;
import java.util.Queue;
class Node {
int x;
int y;
int d;
Node(int x,int y,int d) {
this.x = x;
this.y = y;
this.d = d;
}
};
public class Problem3{
private static final int r[] = {-1,1};
private static final int c[] = {0,-1,1,0};
public static ArrayList<Pos> findPath(Pos start,Pos end,boolean maze[][]){
ArrayList<Pos> path = new ArrayList<Pos>();
path.add(start);
// Get the x and y values from both start and end Pos
// currX and currY is initially start Pos
int currX = start.x;
int currY = start.y;
int endX = end.x;
int endY = end.y;
// Set to size of maze
boolean[][] visited = new boolean[6][6];
Queue<Node> q = new ArrayDeque<>();
visited[currX][currY] = true;
q.add(new Node(currX,currY,0));
int min_d = Integer.MAX_VALUE;
while (!q.isEmpty()) {
// Pop front node and process
Node node = q.poll();
currX = node.x;
currY = node.y;
int d = node.d;
// If end is found,stop
if (currX == endX && currY == endY)
{
path.add(end);
min_d = d;
break;
}
// check all 4 directions from curr cell
for (int k = 0; k < 4; k++)
{
if (isValid(maze,visited,currX + r[k],currY + c[k]))
{
// mark as visited and add to path
visited[currX + r[k]][currY + c[k]] = true;
q.add(new Node(currX + r[k],currY + c[k],d + 1));
path.add(new Pos(currX,currY));
}
}
}
// If path is empty,return null. Else return path
if (path.isEmpty()) {
return null;
}
else {
return path;
}
}
// Checks if cell is traversable or visited
private static boolean isValid(boolean maze[][],boolean visited[][],int r,int c) {
return maze[r][c] && !visited[r][c];
}
}
代码在另一个类中运行,该类从.in
文件中读取迷宫,然后在所述迷宫上运行我的算法。如果返回ArrayList<Pos> path
,它将打印每个元素。如果不是,则仅打印“不可解决”。可以说我有文件test.in并运行java driver < test.in
:
6 6
######
#A...#
#.##.#
#.##.#
#.B..#
######
我希望输出为:
[1,1]
[2,1]
[3,1]
[4,2]
但这就是我得到的:
[1,1]
[1,2]
[2,3]
[3,4]
[4,2]
通过查看输出,似乎算法找到了最短路径,但是每个坐标打印两次。此外,x和y值会翻转,并且开始坐标将被打印3次。非常感谢您提供有关解决问题的帮助。