寻找最短路径Dijkstra算法
2024-10-10 10:15:40
1 /**
2 * 1.对于T中的每个顶点u,找到u的具有最小权重的连接边。所有到u的连接边都存储在queues.get(u)中。queues.get(u).peek()返回拥有最小权值
3 * 的连接边。如果e.v已经在T中,将e从queues.get(u)中删除。
4 * 2.比较所有这些边,并且找到那个具有cost[u]+e.getWeight()最小值的边。
5 */
6 public ShortestPathTree getShortestPath(int sourceIndex){
7 List<Integer> T = new ArrayList<Integer>();
8 T.add(sourceIndex);
9
10 int numberOfVertices = vertices.size();
11
12 int[] parent = new int[numberOfVertices];
13 parent[sourceIndex] = -1;
14
15 int[] costs = new int[numberOfVertices];
16 for (int i = 0; i < costs.length; i++) {
17 costs[i] = Integer.MAX_VALUE;
18 }
19 costs[sourceIndex] = 0;
20
21 List<PriorityQueue<WeightedEdge>> queues = deepClone(this.queues);
22
23 while (T.size() < numberOfVertices) {
24 int v = -1;
25 int smallestCost = Integer.MAX_VALUE;
26 for (int u:T) {
27 while(!queues.get(u).isEmpty() &&
28 T.contains(queues.get(u).peek().v))
29 {
30 queues.get(u).remove();
31 }
32 if(queues.get(u).isEmpty()){
33 continue;
34 }
35 WeightedEdge e = queues.get(u).peek();
36 if(costs[u] + e.weight < smallestCost){
37 v = e.v;
38 smallestCost = costs[u] + e.weight;
39 parent[v] = u;
40 }
41 }
42 T.add(v);
43 costs[v] = smallestCost;
44 }
45 return new ShortestPathTree(sourceIndex, parent, T, costs);
46 }
最新文章
- Apache Shiro系列三,概述 —— 10分钟入门
- 《LINUX内核设计与实现》读书笔记之第五章
- HTML中表格元素TABLE,TR,TD及属性的语法
- du: fts_read 失败: 无法分配内存
- xfs文件系统
- 模仿QQ空间 网页设计
- 最小化安装Centos7后的部署(个人)
- A题 - A + B Problem
- 命令行方式运行yii2程序
- 学习笔记——适配器模式Adapter
- 团队作业8——第二次项目冲刺(Bata版本)--第二天
- JavaScript的数据结构和算法
- [物理学与PDEs]第1章第8节 静电场和静磁场 8.2 稳定电流的电场
- Codeforces 1109D Sasha and Interesting Fact from Graph Theory (看题解) 组合数学
- vue 生产环境 background 背景图不显示原因
- java之Stack详细介绍
- eclipse使用struts2找不到action方法或找不到action的错误记录
- JUnit 3一个例子就懂
- AS3获取对象类名,getDefinitionByName,getQualifiedClassName,getQualifiedSuperclassName
- CSS中定义a:link、a:visited、a:hover、a:active顺序