[英]Printing the shortest path with BFS
I am creating a maze solver which uses Breadth First Search
algorithm and I'm wondering if I can somehow print the path on the grid instead of just printing the distance value it travelled in order to find the exit.我正在创建一个使用
Breadth First Search
算法的迷宫求解器,我想知道是否可以以某种方式在网格上打印路径,而不仅仅是打印它经过的距离值以找到出口。 Here is the code down below and thanks in advance.这是下面的代码,提前致谢。
public List<Coords> solve(int x, int y) {
Queue<Coords> q = new LinkedList<>();
List<Coords> visited = new ArrayList<>();
Coords start = new Coords(x,y);
q.add(start);
visited.add(start);
while(!q.isEmpty()) {
Coords get = q.poll();
if(maze[get.x][get.y] == 3) {
System.out.println("found an exit!");
System.out.println("Distance: " + get.dist);
break;
}
if(!visited.contains(get)) {
visited.add(get);
}
if(isValid(get.x-1, get.y)) {
q.add(new Coords(get.x-1, get.y, get.dist+1));
}
if(isValid(get.x, get.y-1)) {
q.add(new Coords(get.x, get.y-1, get.dist+1));
}
if(isValid(get.x+1, get.y)) {
q.add(new Coords(get.x+1, get.y, get.dist+1));
}
if(isValid(get.x, get.y+1)) {
q.add(new Coords(get.x, get.y+1, get.dist+1));
}
}
return visited;
}
}
The output is: found an exit: Distance: 20
output是:
found an exit: Distance: 20
I'm not sure I understand the question perfectly, but don't you already have this data in your Queue<Coords> q
object?我不确定我是否完全理解这个问题,但是您的
Queue<Coords> q
object 中是否已经有了这些数据?
If that's the case, then you could have something like this:如果是这样的话,那么你可以有这样的事情:
if (maze[get.x][get.y] == 3) {
System.out.println("found an exit!");
System.out.println("Distance: " + get.dist);
for(Coords c : q) {
System.out.println(c);
}
break;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.