Dijkstra链路状态选路算法

时间:2022-03-31 12:46:44

Dijkstra链路状态选路算法

 

步骤 N1 D(v),p(v) D(w),p(w) D(x),p(x) D(y),p(y) D(z),p(z)
0 u 2,u 5,u 1,u 无穷大 无穷大
1 ux 2,u 4,x   2,x 无穷大
2 uxy 2,u 3,y     4,y
3 uxyv   3,y     4,y
4 uxyvw         4,y
5 uxyvwz          

 

D(o):随着算法进行本次迭代,从源节点到目的节点o的最低费用路径的费用。

p(o):从源节点到目的节点o沿着当前最低费用路径的前一节点(o的邻居)。

N1:节点子集,如果从源节点到目的节点o的最低费用路径已确知,o在N1中。

LS算法:

Initialization:

  N1 = {u}

  for all node o

    if o is a neighbor of u

      then D(o) = c(u,o)

    else D(v) = 无穷大

Loop

  find w not in N1 such that D(w) is a minium

  add w to N1

  update D(o) for each neighbor o of w  and not in N1:

      D(o) = min(D(o), D(o) + c(w,o))

/* new cost to o is either old cost to o or known  least path cost to w plus cost from w to o*/

until N1 = N

 Java实现:

 1 public class Dijkstra {
2
3 private static int MAX = 1000;
4
5 /**
6 * @param args
7 */
8 public static void main(String[] args) {
9 dijkstra();
10 }
11
12 public static void dijkstra(){
13 //图的邻接矩阵
14 /* 节点到自身的距离为0,到非邻居节点的距离为MAX*/
15 int[][] matrix = {
16 {0, 2, 5, 1, MAX, MAX},
17 {2, 0, 3, 2, MAX, MAX},
18 {5, 3, 0, 3, 1, 5},
19 {1, 2, 3, 0, 1, MAX},
20 {MAX,MAX,1, 1, 0, 2},
21 {MAX,MAX,5, MAX,2, 0}
22 };
23
24 int[] isVisited = new int[6];
25 int[] dist = new int[6];
26 int[] pre = new int[6];
27
28 dist[0] = 0;
29 isVisited[0] = 1;
30
31 /* 初始化 距离向量*/
32 for (int i = 1; i < dist.length; i++) {
33 dist[i] = matrix[0][i];
34
35 /* 当前最低费用路径的前一节点为0 */
36 if (dist[i] < MAX) {
37 pre[i] = 0;
38 }
39 }
40
41 for(int j = 1; j < pre.length; j++){
42
43 /* 需找前一次的最短路径的节点 */
44 int minLen = MAX;
45 int n = 0;
46 for (int i = 1; i < dist.length; i++) {
47 /* 未被确认的节点 */
48 if (dist[i] < minLen && isVisited[i] == 0) {
49 minLen = dist[i];
50 /* 确定当前最低费用路径的前一节点*/
51 n = i;
52 }
53 }
54
55 /* 确认节点 */
56 isVisited[n] = 1;
57 /* 更新最短路径 */
58 for(int i = 1; i < dist.length; i++){
59 if (isVisited[i] == 0 && matrix[n][i] < MAX && dist[n] + matrix[n][i] < dist[i]) {
60 dist[i] = dist[n] + matrix[n][i];
61 pre[i] = n;
62 }
63 }
64
65 }
66
67 for (int i = 0; i < dist.length; i++) {
68 System.out.print(dist[i] + " ");
69 }
70 System.out.println();
71
72 int m = 5;
73 System.out.print(5 + " ");
74 while(pre[m] != 0){
75 System.out.print(pre[m] + " ");
76 m = pre[m];
77 }
78 System.out.print(0);
79 }
80 }