dijkstra算法java
时间: 2023-09-22 09:10:43 浏览: 113
Dijkstra算法是一种用于解决带权有向图最短路径问题的贪心算法。下面是Java实现Dijkstra算法的示例代码:
```java
import java.util.*;
public class DijkstraAlgorithm {
private static final int MAX = Integer.MAX_VALUE;
public static void main(String[] args) {
int[][] graph = {
{0, 7, 9, MAX, MAX, 14},
{7, 0, 10, 15, MAX, MAX},
{9, 10, 0, 11, MAX, 2},
{MAX, 15, 11, 0, 6, MAX},
{MAX, MAX, MAX, 6, 0, 9},
{14, MAX, 2, MAX, 9, 0}
};
dijkstra(graph, 0);
}
public static void dijkstra(int[][] graph, int start) {
int n = graph.length;
int[] dist = new int[n];
boolean[] visited = new boolean[n];
Arrays.fill(dist, MAX);
dist[start] = 0;
for (int i = 0; i < n - 1; i++) {
int u = minDistance(dist, visited);
visited[u] = true;
for (int v = 0; v < n; v++) {
if (!visited[v] && graph[u][v] != MAX && dist[u] != MAX
&& dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
}
printSolution(dist);
}
public static int minDistance(int[] dist, boolean[] visited) {
int min = MAX, minIndex = -1;
for (int i = 0; i < dist.length; i++) {
if (!visited[i] && dist[i] <= min) {
min = dist[i];
minIndex = i;
}
}
return minIndex;
}
public static void printSolution(int[] dist) {
System.out.println("Vertex \t Distance from Source");
for (int i = 0; i < dist.length; i++) {
System.out.println(i + " \t " + dist[i]);
}
}
}
```
在这个示例中,我们定义了一个6 x 6的带权有向图,并使用Dijkstra算法计算从顶点0到其他顶点的最短路径。算法会输出每个顶点的最短距离。
阅读全文