给定带权有向图G =(V,E),其中每条边的权是非负实数。另外,还给定V中的一个顶点,称为源。现在要计算从源到所有其他各顶点的最短路长度。这里路的长度是指路上各边权之和。JAVA代码实现
时间: 2024-02-17 18:03:58 浏览: 69
有向图的邻接表(C语言)
以下是使用 Java 实现 Dijkstra 算法计算最短路径的示例代码:
```java
import java.util.*;
public class Dijkstra {
public static void main(String[] args) {
int[][] graph = {
{0, 6, 3, 0, 0},
{0, 0, 0, 2, 1},
{0, 1, 0, 4, 0},
{0, 0, 0, 0, 2},
{3, 0, 0, 0, 0}
};
int source = 0;
int[] dist = dijkstra(graph, source);
System.out.println(Arrays.toString(dist));
}
public static int[] dijkstra(int[][] graph, int source) {
int n = graph.length;
boolean[] visited = new boolean[n];
int[] dist = new int[n];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[source] = 0;
for (int i = 0; i < n; i++) {
int u = findMinDist(dist, visited);
visited[u] = true;
for (int v = 0; v < n; v++) {
if (!visited[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
}
return dist;
}
public static int findMinDist(int[] dist, boolean[] visited) {
int minDist = Integer.MAX_VALUE;
int minIndex = -1;
for (int i = 0; i < dist.length; i++) {
if (!visited[i] && dist[i] < minDist) {
minDist = dist[i];
minIndex = i;
}
}
return minIndex;
}
}
```
其中,`graph` 是带权有向图的邻接矩阵表示,`source` 是源节点的下标。`dijkstra` 方法返回从源节点到所有其他节点的最短路径长度数组。
阅读全文