在图论中,迪杰斯特拉算法是最为经典的路径,它采用贪心算法,遍历到始点距离最近且未访问过的顶点的邻接节点,直到扩展到终点为止,计算解决了有权图中最短路径的问题 代码: import java.util.Scanner; public class DiJisTra { public static int MaxValue = 10000; public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("请输入顶点数与边数"); //存顶点数 int vertex = input.nextInt(); //存边数 int edge = input.nextInt(); int[][] matrix = new int[vertex][vertex]; //存顶点关系的二位数组,邻接矩阵 for (int i = 0; i < vertex; i++) { for (int j = 0; j < vertex; j++) { matrix[i][j] = MaxValue; //将矩阵中每个关系初始化为10000,即没有关系 } } //存边上的权值 eg:A->B 10 for (int i = 0; i < edge; i++) { System.out.println("请输入第" + (i + 1) + "边与其权值:"); int source = input.nextInt(); int target = input.nextInt(); int weight = input.nextInt(); matrix[source][target] = weight; //用矩阵存储接结点间的关系 } int source = input.nextInt(); dijStr(matrix, source); //调用dijStr算法计算最短路径 } public static void dijStr(int[][] matrix, int source) { //最短路径长度 int[] shortest = new int[matrix.length]; //判断该点的最短路径是否求出 int[] visited = new int[matrix.length]; //存储输出路径 String[] path = new String[matrix.length]; for (int i = 0; i < matrix.length; i++) { path[i] = new String(source + "->" + i); } shortest[source] = 0; visited[source] = -1; for (int i = 1; i < matrix.length; i++) { int min = Integer.MAX_VALUE; int index = -1; for (int j = 0; j < matrix.length; j++) { //求出的最短路径的结点不需再计算,并判断加入的结点是否有更短路径 if (visited[j] == 0 && matrix[source][j] < min) { //若该节点的最短路径未被求出,则进行操作 min = matrix[source][j]; index = j; } } shortest[index] = min; visited[index] = 1; for (int m = 0; m < matrix.length; m++) { if (visited[m] == 0 && matrix[source][index] + matrix[index][m] < matrix[source][m]) { matrix[source][m] = matrix[source][index] + matrix[index][m]; path[m] = path[index] + "->" + m; } } } //打印最短路径 for (int i = 0; i < matrix.length; i++) { if (i != source) { if (shortest[i] == MaxValue) { System.out.println(source + "到" + i + "不可达"); } else { System.out.println(source + "到" + i + "的最短路径为:" + path[i] + ",最短距离是:" + shortest[i]); } } } } }
05-24
2053
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
03-20
1408
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-22
789
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-20
393
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)