如何找到所有最短路径 [英] How to find all shortest paths

查看:153
本文介绍了如何找到所有最短路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张图,我想找到两个节点之间的所有最短路径.我通过 BFS 找到了两个节点之间的最短路径.但是,如果存在多个,它只会给我一条最短路径.

I have a graph and I want to find all shortest paths between two nodes. I've found a shortest path between two nodes by BFS. However, it just gives me one of the shortest paths if there exists one more than.

如何使用 BFS 获得所有这些?

How could I get all of them using BFS?

我已经用著名的 BFS 伪代码实现了我的代码.
另外,我有一个邻接列表向量,它包含所有节点的邻接顶点.

I've implement my code from well-known BFS pseudocode.
Also, I have a adjacency list vector which holds adjacency vertices for all nodes.

推荐答案

更简单的方法是使用 dfs 查找从源到目标的所有路径.现在找出这些路径中最短的路径.这是一个 sudo 代码:

A simpler way is to find all paths from source to destination using dfs. Now find the shortest paths among these paths. Here is a sudo code:

dfs(p,len)
      if(visited[p])
         return

      if(p== destination)
          paths.append(len)

          return
      visited[p]=1
      for each w adjacent to p
           dfs(w,len+1)
      visited[p]=0

您可以通过维护路径数组来找到路径.我会把它留给你作为任务

You can find the path by maintaining an array for paths. I will leave that to you as an assignment

这篇关于如何找到所有最短路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆