package dijkstra; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class Dijkstra { public static int U = 99999999; // 此路不通 static class Path2Len { public List<Integer> shortPath; public int shortLen; public Path2Len(int start) { this.shortPath = new ArrayList<Integer>(); this.shortPath.add(start); this.shortLen = U; } } public static void main(String[] args) { int[][] graph = { { 0, 10, U, 30, 100 }, { U, 0, 50, U, U }, { U, U, 0, U, 10 }, { U, U, 20, 0, 60 }, { U, U, U, U, 0 } }; int start = 0; Path2Len[] path2Len = dijkstra(graph, start); for (int i = 0; i < path2Len.length; i++) { System.out.println("从" + start + "出发到" + i + "的最短长度为:" + path2Len[i].shortLen + ", 具体路径:" + path2Len[i].shortPath); } } public static Path2Len[] dijkstra(int[][] graph, int start) { int vertexCount = graph.length; // 顶点数 // 一维数组path2LenArray,保存出发点到其余点的距离和路径 Path2Len[] path2LenArray = new Path2Len[vertexCount]; // 保存未访问的点 Set<Integer> unVistedVetrixSet = new HashSet<Integer>(); // 初始化path2LenArray,用连接矩阵初始化 for (int i = 0; i < vertexCount; i++) { Path2Len path2Len = new Path2Len(start); path2Len.shortLen = graph[start][i]; path2LenArray[i] = path2Len; unVistedVetrixSet.add(i); } // 出发点已经访问 unVistedVetrixSet.remove(start); // 查询 N-1 次 while (!unVistedVetrixSet.isEmpty()) { // 先从path2LenArray 查询一个未访问的最近点 int minIndex = -1; int minLen = U; for (int column = 0; column < path2LenArray.length; column++) { if (unVistedVetrixSet.contains(column)) { if (path2LenArray[column].shortLen < minLen) { minLen = path2LenArray[column].shortLen; minIndex = column; } } } if (minLen >= U) { break; } // 查找到最近点minIndex,设置为已经访问 unVistedVetrixSet.remove(minIndex); System.out.println("minIndex = " + minIndex + " found "); // 根据查找到的minIndex 和连接矩阵,更新path2LenArray for (int column = 0; column < path2LenArray.length; column++) { if (unVistedVetrixSet.contains(column)) { int old_start_2_column = path2LenArray[column].shortLen; int new_start_2_column = path2LenArray[minIndex].shortLen + graph[minIndex][column]; if (new_start_2_column < old_start_2_column) { path2LenArray[column].shortLen = new_start_2_column; path2LenArray[column].shortPath.clear(); path2LenArray[column].shortPath .addAll(path2LenArray[minIndex].shortPath); path2LenArray[column].shortPath.add(column); } } } } return path2LenArray; } }
可以看出,Dijstra算法的时间复杂度为N^2