[英]Find all shortest paths in an unweighted graph from a source to a destination
我想在未加权图中找到所有最短路径。 在我的第一次尝试中,我设法使用BFS仅找到一条短路径。 我使用堆栈来保存最短路径和BFS队列。 visited
向量用于标记节点是否被拜访。 这是我在Java中所做的:
public ArrayList<Integer> BFS(int source, int dest) {
ArrayList<Integer> shortestPathList = new ArrayList<Integer>();
boolean[] visited = new boolean[100];
Queue<Integer> q = new LinkedList<Integer>();
Stack<Integer> pathStack = new Stack<Integer>();
q.add(source);
pathStack.add(source);
visited[source] = true;
while (!q.isEmpty()) {
int u = q.poll();
for (int v : graph.getNeighboursOf(u)) {
if (!visited[v]) {
q.add(v);
visited[v] = true;
pathStack.add(v);
if (u == dest)
break;
}
}
}
// To find the path
int node, currentSrc = dest;
shortestPathList.add(dest);
while (!pathStack.isEmpty()) {
node = pathStack.pop();
if (graph.isNeighbor(currentSrc, node)) {
shortestPathList.add(node);
currentSrc = node;
if (node == source)
break;
}
}
return shortestPathList;
}
ArrayList shortestPathList
仅包含一个短路径。 我可以修改此BFS来查找所有最短路径,还是需要制作其他算法?
在您的代码中
if (!visited[v]) {...}
确保您仅使用每个v的第一个最短路径。而不是忽略其他v,您需要考虑所有v(只要达到相同长度的路径,就需要到达源)可能)。
如果跟踪到源的访问节点的最小距离,则将找到到目标的所有最短路径:
function shortest_paths_to(dest):
if dest == source:
yield path([n])
return
for each vertex n in neighbours(dest):
if distance_from_source(n) < distance_from_source(dest):
for each path p in shortest_paths_to(n):
p.append(dest)
yield p
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.