1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| package graph;
import com.alibaba.fastjson.JSON; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors;
import java.util.*;
public class Dijkstra { public static void main(String[] args) {
Graph graph = Graph.build("A-B:16,B-C:10,C-D:3,D-E:4,E-F:8,F-A:14,B-G:7,C-G:6,E-G:2,F-G:9,A-G:12,C-E:5"); Map<String, Entry> visited = new HashMap<>(); PriorityQueue<Entry> queue = new PriorityQueue<>(Comparator.comparing(Entry::getDistance));
String startVertex = "C"; queue.offer(new Entry(startVertex, null, 0));
while (!queue.isEmpty()) { Entry min = queue.poll(); String currentVertex = min.getVertex();
if (visited.containsKey(currentVertex)) { continue; }
visited.put(currentVertex, min);
for (Graph.Edge edge : graph.getVertexEdges(currentVertex)) { if (visited.containsKey(edge.getEnd())) { continue; }
queue.offer(new Entry(edge.getEnd(), currentVertex, edge.getWeight() + min.getDistance())); } }
System.out.println(JSON.toJSONString(visited, true));
for (String vertex : graph.getVertices()) { System.out.printf("\n最短路径: %s 到 %s,距离 %.2f\n", startVertex, vertex, visited.get(vertex).getDistance());
List<String> path = new LinkedList<>(); Entry current = visited.get(vertex); while (current != null) { path.add(0, current.getVertex()); current = visited.get(current.getPrevVertex()); } System.out.println(String.join("->", path)); } }
@Getter @Setter @Accessors(chain = true) public static class Entry { String vertex; String prevVertex; double distance;
public Entry(String vertex, String prevVertex, double distance) { this.vertex = vertex; this.prevVertex = prevVertex; this.distance = distance; } } }
|