Dijkstra's algorithm的简单实现【java】
在比较简单的情况下,当单条路径的距离固定为一的时候(比如计算分子中各个原子的距离)可以用表格来处理。只需要adjacency matrix.
private static int[][] doDijkstra(int[][] adjList) {
int n = adjList.length;
int[][] distMatrix = new int[n][n];
for (int i = 0; i < n; ++i) { //对于列表中的每一行
for (int j = 0; j < n; ++j) //距离先设为无限大
distMatrix[i][j] = Integer.MAX_VALUE;
Set<Integer> layer = new HashSet<Integer>();//对于表中的每一列,考虑每个原子
layer.add(i);
distMatrix[i][i] = 0;
int distance = 1;
while (!layer.isEmpty()) { //当待考虑对象不为空时
Set<Integer> nextLayer = new HashSet<Integer>();
for (Integer c : layer) { //考虑当前层的每个对象的所有neighbor
for (int d : adjList[c]) { // 将这些neighbor与中心原子的距离记录下来
if (distMatrix[i][d] == Integer.MAX_VALUE) {
distMatrix[i][d] = distance;
nextLayer.add(d); //将neighbors加入待考虑集合
}
}
}
layer = nextLayer;
distance += 1;
}
}
可以看看和比较复杂的Dijkstra's algorithm伪代码的区别
1 function Dijkstra(Graph, source):
2 for each vertex v in Graph: // Initializations
3 dist[v] := infinity ; // Unknown distance function from source to v
4 previous[v] := undefined ; // Previous node in optimal path from source
5 end for ;
6 dist[source] := 0 ; // Distance from source to source
7 Q := the set of all nodes in Graph ;
// All nodes in the graph are unoptimized - thus are in Q
8 while Q is not empty: // The main loop
9 u := vertex in Q with smallest dist[] ;
10 if dist[u] = infinity:
11 break ; // all remaining vertices are inaccessible from source
12 fi ;
13 remove u from Q ;
14 for each neighbor v of u: // where v has not yet been removed from Q.
15 alt := dist[u] + dist_between(u, v) ;
16 if alt < dist[v]: // Relax (u,v,a)
17 dist[v] := alt ;
18 previous[v] := u ;
19 fi ;
20 end for ;
21 end while ;
22 return dist[] ;
23 end Dijkstra.

浙公网安备 33010602011771号