我已经编写了一个函数,用于计算使用BFS是否可以从源顶点到达目标顶点。现在我需要跟踪我用来达到顶点的路径。我想这应该是一个小小的调整,我们可以将节点添加到我的路径数组列表中。有人请帮助我。使用BFS的2个节点之间的路径
public Boolean isReachable(Node destination) {
ArrayList<Node> visited = new ArrayList<>();
LinkedList<Node> queue = new LinkedList<>();
ArrayList<Node> path = new ArrayList<>();
queue.add(this);
while (queue.size() != 0) {
Node source = queue.poll();
for (Node node : source.adjacentNodes) {
if (node.equals(destination))
return true;
if (!visited.contains(node)) {
visited.add(node);
queue.add(node);
}
}
}
return false;
}
可能重复[只返回实际最短路径中的顶点](http://stackoverflow.com/questions/5463505/returning-only-the-vertices-in-act-shortest-path) –