最短路(一)Single Source

最短路(一) 单起点


在一个图中,给定起点,求到别的点的最短路。

Dijkstra

创建一个距离数组,记录当前起点到该点的最短距离,起点距离初始化为0,其余点初始化为正无穷。
创建最小堆pq,用来存放当前已经找到最小距离的点,初始化为起点,比较原则是根据当前的最小距离。
当堆内仍有元素为处理完时:
- 取出当前距离最小的未访问的点
- 更新它的neighbor的通过该点的距离(如果比原来记录的小的话)并将其加入堆中

正确性:假设当前距离最小的点 V V V对应的距离 S S S并不是它的最小距离,也就是有另一条路径 p = ( v 1 , v 2 , . . . , v m , V ) p=(v_{1}, v_{2}, ..., v_{m}, V) p=(v1,v2,...,vm,V)使得路径最短,那么从起点到p中任意点的路径都比 S S S要小,根据算法 v 1 , v 2 , . . . , v m v_{1}, v_{2}, ..., v_{m} v1,v2,...,vm都应该在 V V V之前就被访问了,在访问 v m v_{m} vm时, V V V作为它的邻点,距离已经被更新成p的长度,又因为 p < S p \lt S p<S,所以根据算法一定有该最小距离比 S S S先被访问到,矛盾。

例子
Dijkstra例

代码

// 图用邻接链表表示,Pair中第一个数为另一端点,第二个数为权重
public static int[] dijkstraAlgo(List<List<Pair<Integer, Integer>>> graph, int start) {
   
        List<Integer> seq = new ArrayList<>();
        int[] distance = new int[graph.size()];
        int[] visited = new int[graph.size()];
        Arrays.fill(distance, Integer.MAX_VALUE);
        distance
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Java语言实现多源最短路算法的示例代码: ``` import java.util.*; public class MultiSourceShortestPath { static class Edge { int source, dest, weight; public Edge(int source, int dest, int weight) { this.source = source; this.dest = dest; this.weight = weight; } } static int V, E; static List<Edge>[] graph; public static void main(String[] args) { Scanner sc = new Scanner(System.in); V = sc.nextInt(); E = sc.nextInt(); graph = new ArrayList[V]; for (int i = 0; i < V; i++) { graph[i] = new ArrayList<>(); } for (int i = 0; i < E; i++) { int u = sc.nextInt(); int v = sc.nextInt(); int w = sc.nextInt(); graph[u].add(new Edge(u, v, w)); graph[v].add(new Edge(v, u, w)); } int[] dist = multiSourceShortestPath(); for (int i = 0; i < V; i++) { System.out.print(dist[i] + " "); } } static int[] multiSourceShortestPath() { int[] dist = new int[V]; Arrays.fill(dist, Integer.MAX_VALUE); Queue<Integer> q = new LinkedList<>(); for (int i = 0; i < V; i++) { q.add(i); dist[i] = 0; } while (!q.isEmpty()) { int u = q.poll(); for (Edge e : graph[u]) { int v = e.dest; int w = e.weight; if (dist[v] > dist[u] + w) { dist[v] = dist[u] + w; q.add(v); } } } return dist; } } ``` 该算法使用广度优先搜索(BFS)实现。首先将所有顶点添加到队列中,并将它们的距离初始化为0。然后,对于队列中的每个顶点,遍历它的所有邻居,并更新它们到源点的距离。如果距离被更新,则将邻居添加到队列中以进一步处理。 该算法的时间复杂度为O(V+E),其中V是顶点数,E是边数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值