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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
| public class NetworkRouting {
static class Edge {
int to;
int weight;
Edge(int to, int weight) {
this.to = to;
this.weight = weight;
}
}
/**
* Dijkstra算法 - 单源最短路径
* 贪心策略:每次选择距离最近的未访问节点
* 时间复杂度:O((V + E) log V)
*/
public int[] dijkstra(List<List<Edge>> graph, int start) {
int n = graph.size();
int[] dist = new int[n];
boolean[] visited = new boolean[n];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[start] = 0;
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[1] - b[1]);
pq.offer(new int[]{start, 0});
while (!pq.isEmpty()) {
int[] current = pq.poll();
int u = current[0];
if (visited[u]) continue;
visited[u] = true;
// 更新邻接节点的距离
for (Edge edge : graph.get(u)) {
int v = edge.to;
int weight = edge.weight;
if (!visited[v] && dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
pq.offer(new int[]{v, dist[v]});
}
}
}
return dist;
}
/**
* 构建路由表
*/
public void buildRoutingTable(List<List<Edge>> graph, int router) {
int[] distances = dijkstra(graph, router);
System.out.println("路由器 " + router + " 的路由表:");
System.out.println("目标\t距离\t下一跳");
System.out.println("--------------------");
for (int i = 0; i < distances.length; i++) {
if (i != router) {
String distance = distances[i] == Integer.MAX_VALUE ? "∞" : String.valueOf(distances[i]);
System.out.println(i + "\t" + distance + "\t" + getNextHop(graph, router, i));
}
}
}
private int getNextHop(List<List<Edge>> graph, int start, int target) {
// 简化版本,实际实现需要记录路径
for (Edge edge : graph.get(start)) {
if (edge.to == target) {
return target;
}
}
return -1; // 需要更复杂的路径重构
}
public static void main(String[] args) {
NetworkRouting routing = new NetworkRouting();
// 构建网络图
int n = 5;
List<List<Edge>> graph = new ArrayList<>();
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}
// 添加边(双向)
addBidirectionalEdge(graph, 0, 1, 4);
addBidirectionalEdge(graph, 0, 2, 2);
addBidirectionalEdge(graph, 1, 2, 1);
addBidirectionalEdge(graph, 1, 3, 5);
addBidirectionalEdge(graph, 2, 3, 8);
addBidirectionalEdge(graph, 2, 4, 10);
addBidirectionalEdge(graph, 3, 4, 2);
// 从节点0开始的最短路径
int[] distances = routing.dijkstra(graph, 0);
System.out.println("从节点0到各节点的最短距离:");
for (int i = 0; i < distances.length; i++) {
System.out.println("到节点" + i + ": " + distances[i]);
}
}
private static void addBidirectionalEdge(List<List<Edge>> graph, int u, int v, int weight) {
graph.get(u).add(new Edge(v, weight));
graph.get(v).add(new Edge(u, weight));
}
}
|