[英]How to find a path from one vertex to another in a tree using breadth first search?
I am trying to implement a BFS that returns a path from a
to b
in form of a list of vertices.我正在尝试实现一个 BFS, a
以顶点列表的形式返回从a
到b
的路径。 I am implementing this BFS on a tree so I know it will be the shortest path if I can find one.我正在一棵树上实现这个 BFS,所以我知道如果我能找到它,它将是最短的路径。 However, so far my research has only led me to find BSF algorithms that search and find nodes, rather than return a path.然而,到目前为止,我的研究只是让我找到了搜索和查找节点的 BSF 算法,而不是返回路径。
The input that I am dealing with is an adjacency matrix of the Minimum Spanning Tree.我正在处理的输入是最小生成树的邻接矩阵。 I must take this and find path from one point to the other.我必须接受这个并找到从一个点到另一个点的路径。
If you really want to use BFS to solve this, to trace the path from source to destination you need to store the parent of each node visited.如果你真的想使用 BFS 来解决这个问题,要跟踪从源到目标的路径,你需要存储每个访问过的节点的父节点。 Here's a sample BFS without optimizations.这是一个没有优化的示例 BFS。
import java.util.*;
public class bfs {
static class Node {
Node parent;
int x;
Node (int x) {
this (x, null);
}
Node (int x, Node parent) {
this.parent = parent;
this.x = x;
}
void trace () {
if (parent == null) {
System.out.print (x);
} else {
parent.trace ();
System.out.print ("->" + x);
}
}
}
static void bfs (int start, int goal, int[][] adj) {
List<Node> list = new ArrayList<> ();
list.add (new Node (start));
while (!list.isEmpty ()) {
Node cur = list.remove (0);
if (cur.x == goal) {
cur.trace ();
break;
} else {
for (int i = 0; i < adj[cur.x].length; i++) {
if (adj[cur.x][i] == 1) {
list.add (new Node (i, cur));
}
}
}
}
}
public static void main (String[] args) {
int[][] adjacency_matrix = {
{0, 1, 1, 0, 0},
{1, 0, 0, 1, 0},
{1, 0, 0, 0, 0},
{0, 1, 0, 0, 1},
{0, 0, 0, 1, 0}
};
int start = 0;
int goal = 4;
bfs (start, goal, adjacency_matrix);
}
}
Dijkstra or A* is probably what you want to use. Dijkstra 或 A* 可能是您想要使用的。 It depends, though.不过也要看情况。 What you seem to be describing is a pathfinding algorithm, not a node search.您似乎在描述的是寻路算法,而不是节点搜索。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.