迪杰斯特拉算法 java
时间: 2023-10-29 12:08:12 浏览: 94
java实现迪杰斯特拉算法
5星 · 资源好评率100%
迪杰斯特拉算法是一种用于解决带权有向图或无向图的单源最短路径问题的算法。它可以计算出从源点到图中所有其他节点的最短路径。该算法的基本思想是从源点开始,依次遍历与其相邻的节点,并更新这些节点到源点的距离。在遍历过程中,每次选择距离源点最近的节点作为下一个遍历的节点,直到遍历完所有节点为止。迪杰斯特拉算法的时间复杂度为O(n^2),其中n为节点数。在实际应用中,可以使用优先队列等数据结构来优化算法的效率。
以下是迪杰斯特拉算法的java代码实现:
```
public class Dijkstra {
public static void dijkstra(int[][] graph, int src) {
int n = graph.length;
int[] dist = new int[n];
boolean[] visited = new boolean[n];
for (int i = 0; i < n; i++) {
dist[i] = Integer.MAX_VALUE;
visited[i] = false;
}
dist[src] = 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] != 0 && dist[u] != Integer.MAX_VALUE && 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 = Integer.MAX_VALUE;
int 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\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,
阅读全文