dijkstra算法求最短路径java代码
时间: 2023-07-29 20:10:48 浏览: 103
以下是 Dijkstra 算法求最短路径的 Java 代码实现:
```java
import java.util.*;
public class DijkstraAlgorithm {
private static final int NO_PARENT = -1;
private static void dijkstra(int[][] adjacencyMatrix, int startVertex) {
int nVertices = adjacencyMatrix[0].length;
int[] shortestDistances = new int[nVertices];
boolean[] visited = new boolean[nVertices];
for (int i = 0; i < nVertices; i++) {
shortestDistances[i] = Integer.MAX_VALUE;
visited[i] = false;
}
shortestDistances[startVertex] = 0;
int[] parents = new int[nVertices];
parents[startVertex] = NO_PARENT;
for (int i = 1; i < nVertices; i++) {
int nearestVertex = -1;
int shortestDistance = Integer.MAX_VALUE;
for (int j = 0; j < nVertices; j++) {
if (!visited[j] && shortestDistances[j] < shortestDistance) {
nearestVertex = j;
shortestDistance = shortestDistances[j];
}
}
visited[nearestVertex] = true;
for (int k = 0; k < nVertices; k++) {
int edgeDistance = adjacencyMatrix[nearestVertex][k];
if (edgeDistance > 0 && ((shortestDistance + edgeDistance) < shortestDistances[k])) {
parents[k] = nearestVertex;
shortestDistances[k] = shortestDistance + edgeDistance;
}
}
}
printSolution(startVertex, shortestDistances, parents);
}
private static void printSolution(int startVertex, int[] distances, int[] parents) {
int nVertices = distances.length;
System.out.print("Vertex\t Distance\tPath");
for (int i = 0; i < nVertices; i++) {
if (i != startVertex) {
System.out.print("\n" + startVertex + " -> ");
System.out.print(i + " \t\t ");
System.out.print(distances[i] + "\t\t");
printPath(i, parents);
}
}
}
private static void printPath(int currentVertex, int[] parents) {
if (currentVertex == NO_PARENT) {
return;
}
printPath(parents[currentVertex], parents);
System.out.print(currentVertex + " ");
}
public static void main(String[] args) {
int[][] adjacencyMatrix = {
{0, 4, 0, 0, 0, 0, 0, 8, 0},
{4, 0, 8, 0, 0, 0, 0, 11, 0},
{0, 8, 0, 7, 0, 4, 0, 0, 2},
{0, 0, 7, 0, 9, 14, 0, 0, 0},
{0, 0, 0, 9, 0, 10, 0, 0, 0},
{0, 0, 4, 14, 10, 0, 2, 0, 0},
{0, 0, 0, 0, 0, 2, 0, 1, 6},
{8, 11, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 2, 0, 0, 0, 6, 7, 0}
};
dijkstra(adjacencyMatrix, 0);
}
}
```
上述代码演示了一个 9 个节点的图,其中每个节点都代表一个城市,而边缘的权重代表这些城市之间的距离。在 `main` 方法中,我们定义了这个图的邻接矩阵,并选择了从第一个节点(即城市 A)开始运行 Dijkstra 算法。最后,我们调用 `dijkstra` 方法来打印最短路径和距离。
阅读全文