用Java实现已知交通图及其运行里程权重,如图1所示。用迪杰斯特拉Dijkstra算法求西宁到其他所有城市的最短路径,打印输出城市起点终点,途经城市和最短路径长度。
时间: 2024-03-03 19:51:36 浏览: 89
dijkstra 迪杰斯特拉 最短路径 java实现
好的,以下是Java实现Dijkstra算法的示例代码,请注意代码注释。
```java
import java.util.Arrays;
public class DijkstraAlgorithm {
// 图的邻接矩阵表示法
private static int[][] graph = {
{0, 2, 1, 4, 5},
{2, 0, 4, 2, 3},
{1, 4, 0, 1, 2},
{4, 2, 1, 0, 1},
{5, 3, 2, 1, 0}
};
private static int start = 0;
private static int[] distances = new int[graph.length];
private static boolean[] visited = new boolean[graph.length];
private static int[] prevNodes = new int[graph.length];
public static void main(String[] args) {
Arrays.fill(distances, Integer.MAX_VALUE);
distances[start] = 0;
prevNodes[start] = -1;
for (int i = 0; i < graph.length - 1; i++) {
int u = findNextNode();
visited[u] = true;
for (int v = 0; v < graph.length; v++) {
if (graph[u][v] > 0 && !visited[v]) {
int newDistance = distances[u] + graph[u][v];
if (newDistance < distances[v]) {
distances[v] = newDistance;
prevNodes[v] = u;
}
}
}
}
for (int i = 0; i < graph.length; i++) {
if (i == start) {
continue;
}
int[] path = getPath(i);
System.out.print("起点:" + start + ",终点:" + i + ",途经城市:");
for (int j = 0; j < path.length; j++) {
if (j == path.length - 1) {
System.out.print(path[j]);
} else {
System.out.print(path[j] + " -> ");
}
}
System.out.println(",最短路径长度:" + distances[i]);
}
}
private static int findNextNode() {
int minDistance = Integer.MAX_VALUE;
int minNode = -1;
for (int i = 0; i < graph.length; i++) {
if (!visited[i] && distances[i] < minDistance) {
minDistance = distances[i];
minNode = i;
}
}
return minNode;
}
private static int[] getPath(int node) {
int[] path = new int[graph.length];
int i = 0;
while (node != -1) {
path[i++] = node;
node = prevNodes[node];
}
return Arrays.copyOfRange(path, 0, i);
}
}
```
希望这份示例代码能够帮助您实现Dijkstra算法并解决问题。
阅读全文