Dijkstra 算法的 Java 实现329
概述
Dijkstra 算法是一种解决加权有向图中单源最短路径问题的贪心算法。对于图中给定的源节点,它计算从源节点到其他所有节点的最短路径。
算法步骤
Dijkstra 算法的步骤如下:1. 初始化:将源节点的距离设为 0,其他所有节点的距离设为无穷大。
2. 选择:从剩余节点中选择距离最小的节点。
3. 松弛:对于该节点的所有相邻节点,更新它们的距离,如果通过该节点找到更短的路径。
4. 重复:重复步骤 2 和 3,直到所有节点的距离都确定。
Java 实现```java
import .*;
public class Dijkstra {
private static class Node implements Comparable {
int vertex;
int distance;
public Node(int vertex, int distance) {
= vertex;
= distance;
}
@Override
public int compareTo(Node other) {
return (, );
}
}
public static Map calculateDistances(Graph graph, int source) {
Map distances = new HashMap();
PriorityQueue pq = new PriorityQueue();
// Initialize distances and add source to priority queue
for (int vertex : ()) {
(vertex, Integer.MAX_VALUE);
}
(source, 0);
(new Node(source, 0));
// While there are nodes in the priority queue
while (!()) {
// Get the node with the smallest distance
Node current = ();
// Visit all neighbors of the current node
for (Edge edge : ()) {
int neighbor = ();
int newDistance = + ();
// If new distance is shorter, update distance and add to priority queue
if (newDistance < (neighbor)) {
(neighbor, newDistance);
(new Node(neighbor, newDistance));
}
}
}
// Return the distances
return distances;
}
// Sample usage
public static void main(String[] args) {
Graph graph = new Graph();
(0, 1, 4);
(0, 2, 2);
(1, 2, 3);
(1, 3, 2);
(2, 3, 3);
Map distances = calculateDistances(graph, 0);
("Distances from source node 0: " + distances);
}
}
```
输出示例```
Distances from source node 0: {0=0, 1=4, 2=2, 3=6}
```
Dijkstra 算法是一种高效的算法,用于解决单源最短路径问题。本文展示了算法的 Java 实现,以及如何使用它来计算从源节点到其他所有节点的最短路径。该算法在各种实际应用中非常有用,例如网络路由和调度问题。
2024-11-24
上一篇:Java 中的文件写入操作
Java方法栈日志的艺术:从错误定位到性能优化的深度指南
https://www.shuihudhg.cn/133725.html
PHP 获取本机端口的全面指南:实践与技巧
https://www.shuihudhg.cn/133724.html
Python内置函数:从核心原理到高级应用,精通Python编程的基石
https://www.shuihudhg.cn/133723.html
Java Stream转数组:从基础到高级,掌握高性能数据转换的艺术
https://www.shuihudhg.cn/133722.html
深入解析:基于Java数组构建简易ATM机系统,从原理到代码实践
https://www.shuihudhg.cn/133721.html
热门文章
Java中数组赋值的全面指南
https://www.shuihudhg.cn/207.html
JavaScript 与 Java:二者有何异同?
https://www.shuihudhg.cn/6764.html
判断 Java 字符串中是否包含特定子字符串
https://www.shuihudhg.cn/3551.html
Java 字符串的切割:分而治之
https://www.shuihudhg.cn/6220.html
Java 输入代码:全面指南
https://www.shuihudhg.cn/1064.html