用java写一个迪杰斯特拉算法
时间: 2024-03-13 18:19:58 浏览: 75
java实现迪杰斯特拉算法
5星 · 资源好评率100%
好的,这是一个关于图论的算法,可以用来求解最短路径问题。你可以参考以下代码:
```java
import java.util.Arrays;
public class DijkstraAlgorithm {
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, Integer.MAX_VALUE);
dist[start] = 0;
for (int i = 0; i < n - 1; i++) {
int u = getMinDist(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];
}
}
}
printDistances(dist);
}
private static int getMinDist(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;
}
private static void printDistances(int[] dist) {
System.out.println("Vertex \t Distance from Source");
for (int i = 0; i < dist.length; i++) {
System.out.println(i + "\t\t" + dist[i]);
}
}
public static void main(String[] args) {
int[][] graph = new int[][]{
{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(graph, 0);
}
}
```
这段代码使用了邻接矩阵来表示图,并实现了 Dijkstra 算法来求解最短路径。如果你需要了解更多关于 Dijkstra 算法的知识,可以参考相关的资料。
阅读全文