简体   繁体   English

查找未加权图中从源到目标的所有最短路径

[英]Find all shortest paths in an unweighted graph from a source to a destination

I'd like to find all shortest path in an unweighted graph. 我想在未加权图中找到所有最短路径。 In my first attempt I managed to find only one short path using BFS. 在我的第一次尝试中,我设法使用BFS仅找到一条短路径。 I used a stack to save the shortest path and a queue for BFS. 我使用堆栈来保存最短路径和BFS队列。 The visited vector is used to mark if a node is visited or not. visited向量用于标记节点是否被拜访。 This is what I've done in Java: 这是我在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;
    }

The ArrayList shortestPathList contains only one short path. ArrayList shortestPathList仅包含一个短路径。 Can I modify this BFS to find all the shortest paths or I need to make another algorithm? 我可以修改此BFS来查找所有最短路径,还是需要制作其他算法?

In your code, 在您的代码中

if (!visited[v]) {...}

ensures you'll only use the first shortest path to each v. Instead of ignoring the others, you'll need to consider all of them (and you'll need to when the source is reached as long as paths of the same length are possible). 确保您仅使用每个v的第​​一个最短路径。而不是忽略其他v,您需要考虑所有v(只要达到相同长度的路径,就需要到达源)可能)。

If you keep track of the minimal distance of visited nodes from the source, then this will find all shortest paths to the destination: 如果跟踪到源的访问节点的最小距离,则将找到到目标的所有最短路径:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM