帮我用java写一个无向图的最短路径算法
时间: 2023-08-28 17:24:01 浏览: 86
无向图最短路径
好的,下面是使用Java编写无向图最短路径算法的示例代码:
```java
import java.util.*;
public class Graph {
private Map<Integer, List<Edge>> edges = new HashMap<>();
public void addEdge(int source, int destination, int weight) {
List<Edge> sourceEdges = edges.getOrDefault(source, new ArrayList<>());
sourceEdges.add(new Edge(source, destination, weight));
edges.put(source, sourceEdges);
List<Edge> destEdges = edges.getOrDefault(destination, new ArrayList<>());
destEdges.add(new Edge(destination, source, weight));
edges.put(destination, destEdges);
}
public List<Integer> shortestPath(int start, int end) {
Map<Integer, Integer> distances = new HashMap<>();
Map<Integer, Integer> parents = new HashMap<>();
PriorityQueue<Node> pq = new PriorityQueue<>(Comparator.comparingInt(n -> n.distance));
Set<Integer> visited = new HashSet<>();
pq.add(new Node(start, 0));
distances.put(start, 0);
while (!pq.isEmpty()) {
Node curr = pq.remove();
int currNode = curr.node;
if (visited.contains(currNode)) {
continue;
}
visited.add(currNode);
if (currNode == end) {
break;
}
for (Edge edge : edges.get(currNode)) {
int nextNode = edge.destination;
int distance = edge.weight;
int totalDistance = distance + distances.get(currNode);
if (!distances.containsKey(nextNode) || totalDistance < distances.get(nextNode)) {
distances.put(nextNode, totalDistance);
parents.put(nextNode, currNode);
pq.add(new Node(nextNode, totalDistance));
}
}
}
List<Integer> path = new ArrayList<>();
int currNode = end;
while (parents.containsKey(currNode)) {
path.add(0, currNode);
currNode = parents.get(currNode);
}
path.add(0, start);
return path;
}
private static class Node {
int node;
int distance;
Node(int node, int distance) {
this.node = node;
this.distance = distance;
}
}
private static class Edge {
int source;
int destination;
int weight;
Edge(int source, int destination, int weight) {
this.source = source;
this.destination = destination;
this.weight = weight;
}
}
}
```
可以使用 `addEdge` 方法添加图的边,然后使用 `shortestPath` 方法计算从起点到终点的最短路径。该算法使用了 Dijkstra 算法,时间复杂度为 O(E log V),其中 E 表示边数,V 表示顶点数。
注意:这只是一个简单的示例代码,实际上,还需要考虑一些边界条件和异常情况。同时,还可以根据实际需求对代码进行优化和改进。
阅读全文