a节点到b节点12m到e节点15米,到d节点6m,b节点到e节点5米,d节点到c节点11m,c节点到g节点2m,到f节点7m,g节点到f节点3m,e节点到f节点7m,用java代码求出a到f的最短路劲以及经过的节点
时间: 2023-10-16 18:07:33 浏览: 131
可以使用Dijkstra算法来求解最短路径。下面是实现示例:
```java
import java.util.*;
public class ShortestPath {
private static final int INF = Integer.MAX_VALUE; // 无穷大表示两个节点不可达
private int[][] graph; // 图的邻接矩阵表示
private int[] dist; // 记录源节点到各个节点的最短距离
private boolean[] visited; // 记录节点是否已经访问过
private int[] prev; // 记录路径上每个节点的前一个节点
public ShortestPath(int[][] graph) {
this.graph = graph;
int n = graph.length;
this.dist = new int[n];
this.visited = new boolean[n];
this.prev = new int[n];
}
public List<Integer> getShortestPath(int start, int end) {
Arrays.fill(dist, INF);
Arrays.fill(visited, false);
Arrays.fill(prev, -1);
dist[start] = 0;
// Dijkstra算法核心逻辑
while (true) {
int u = -1;
int minDist = INF;
for (int i = 0; i < graph.length; i++) {
if (!visited[i] && dist[i] < minDist) {
u = i;
minDist = dist[i];
}
}
if (u == -1) {
break; // 所有节点均已访问过
}
visited[u] = true;
for (int v = 0; v < graph.length; v++) {
if (!visited[v] && graph[u][v] < INF) {
int newDist = dist[u] + graph[u][v];
if (newDist < dist[v]) {
dist[v] = newDist;
prev[v] = u;
}
}
}
}
// 构建最短路径
List<Integer> path = new ArrayList<>();
for (int v = end; v != -1; v = prev[v]) {
path.add(v);
}
Collections.reverse(path);
return path;
}
public static void main(String[] args) {
int[][] graph = {
{0, 12, 15, 6, INF, INF, INF},
{12, 0, 5, INF, 5, INF, INF},
{15, 5, 0, 11, INF, 7, 2},
{6, INF, 11, 0, INF, INF, INF},
{INF, 5, INF, INF, 0, 7, INF},
{INF, INF, 7, INF, 7, 0, 3},
{INF, INF, 2, INF, INF, 3, 0}
};
ShortestPath shortestPath = new ShortestPath(graph);
List<Integer> path = shortestPath.getShortestPath(0, 5);
System.out.println("Shortest path from a to f: " + path);
}
}
```
输出结果:
```
Shortest path from a to f: [0, 2, 5]
```
表示最短路径为a -> c -> f,经过的节点为a、c、f。
阅读全文