用java写一个多源最短路
时间: 2024-04-29 13:24:16 浏览: 16
以下是使用Java语言实现多源最短路算法的示例代码:
```
import java.util.*;
public class MultiSourceShortestPath {
static class Edge {
int source, dest, weight;
public Edge(int source, int dest, int weight) {
this.source = source;
this.dest = dest;
this.weight = weight;
}
}
static int V, E;
static List<Edge>[] graph;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
V = sc.nextInt();
E = sc.nextInt();
graph = new ArrayList[V];
for (int i = 0; i < V; i++) {
graph[i] = new ArrayList<>();
}
for (int i = 0; i < E; i++) {
int u = sc.nextInt();
int v = sc.nextInt();
int w = sc.nextInt();
graph[u].add(new Edge(u, v, w));
graph[v].add(new Edge(v, u, w));
}
int[] dist = multiSourceShortestPath();
for (int i = 0; i < V; i++) {
System.out.print(dist[i] + " ");
}
}
static int[] multiSourceShortestPath() {
int[] dist = new int[V];
Arrays.fill(dist, Integer.MAX_VALUE);
Queue<Integer> q = new LinkedList<>();
for (int i = 0; i < V; i++) {
q.add(i);
dist[i] = 0;
}
while (!q.isEmpty()) {
int u = q.poll();
for (Edge e : graph[u]) {
int v = e.dest;
int w = e.weight;
if (dist[v] > dist[u] + w) {
dist[v] = dist[u] + w;
q.add(v);
}
}
}
return dist;
}
}
```
该算法使用广度优先搜索(BFS)实现。首先将所有顶点添加到队列中,并将它们的距离初始化为0。然后,对于队列中的每个顶点,遍历它的所有邻居,并更新它们到源点的距离。如果距离被更新,则将邻居添加到队列中以进一步处理。
该算法的时间复杂度为O(V+E),其中V是顶点数,E是边数。