写一个java版的迪杰斯特拉算法
时间: 2023-10-25 08:05:06 浏览: 89
java实现迪杰斯特拉算法
5星 · 资源好评率100%
以下是Java版的Dijkstra算法实现:
```java
import java.util.*;
public class DijkstraAlgorithm {
public static void main(String[] args) {
// 构建图
Map<String, Map<String, Integer>> graph = new HashMap<>();
graph.put("A", new HashMap<>());
graph.get("A").put("B", 5);
graph.get("A").put("C", 2);
graph.put("B", new HashMap<>());
graph.get("B").put("D", 4);
graph.get("B").put("E", 2);
graph.put("C", new HashMap<>());
graph.get("C").put("B", 8);
graph.get("C").put("E", 7);
graph.put("D", new HashMap<>());
graph.get("D").put("E", 6);
graph.get("D").put("F", 3);
graph.put("E", new HashMap<>());
graph.get("E").put("F", 1);
graph.put("F", new HashMap<>());
// 运行Dijkstra算法
Map<String, Integer> distances = dijkstra(graph, "A");
// 打印结果
System.out.println(distances);
}
public static Map<String, Integer> dijkstra(Map<String, Map<String, Integer>> graph, String startNode) {
Map<String, Integer> distances = new HashMap<>(); // 节点到起点的距离
Set<String> visited = new HashSet<>(); // 已经访问过的节点集合
PriorityQueue<Node> queue = new PriorityQueue<>(Comparator.comparingInt(n -> n.distance)); // 优先队列,按距离从小到大排序
// 初始化
for (String node : graph.keySet()) {
distances.put(node, Integer.MAX_VALUE); // 所有节点到起点距离先设为无穷大
}
distances.put(startNode, 0); // 起点到起点距离设为0
queue.offer(new Node(startNode, 0)); // 把起点加入队列
while (!queue.isEmpty()) {
Node currentNode = queue.poll(); // 取出距离起点最近的节点
String currentNodeName = currentNode.name;
if (visited.contains(currentNodeName)) {
continue; // 如果节点已经访问过了,就跳过
}
visited.add(currentNodeName); // 把节点标记为已访问
Map<String, Integer> neighbors = graph.get(currentNodeName); // 获取当前节点的邻居节点
for (String neighborName : neighbors.keySet()) {
int distance = neighbors.get(neighborName);
int newDistance = distances.get(currentNodeName) + distance; // 计算从起点到邻居节点的距离
if (newDistance < distances.get(neighborName)) {
distances.put(neighborName, newDistance); // 更新邻居节点到起点的距离
queue.offer(new Node(neighborName, newDistance)); // 把邻居节点加入队列,等待下一轮处理
}
}
}
return distances;
}
private static class Node {
String name; // 节点名称
int distance; // 距离起点的距离
public Node(String name, int distance) {
this.name = name;
this.distance = distance;
}
}
}
```
该算法实现了Dijkstra算法的基本思路,通过优先队列来找到当前距离起点最近的节点,并更新其邻居节点的距离。
阅读全文