单源最短路径问题1 (Bellman-Ford算法)

时间:2022-12-02 22:39:58
/*
单源最短路径问题1 (Bellman-Ford算法)
样例:
5 7
0 1 3
0 3 7
1 2 4
1 3 2
2 3 5
2 4 6
3 4 4
输出:
[0, 3, 7, 5, 9]
*/ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner; public class Test {
//图的顶点数,总边数
static int V, E;
//存储所有的边,大小为顶点数
static ArrayList<Edge>[] Edges;
static int[] d; public static void main(String[] args) {
creatGraph();
shortPath(0);
System.out.println(Arrays.toString(d));
} static void shortPath(int start) {
d=new int[V];
Arrays.fill(d,999999);
d[start]=0;
for (int v = 0; v < V; v++) {
for (int i = 0; i < Edges[v].size(); i++) {
Edge next = Edges[v].get(i);
d[next.v] = Math.min(d[v] + next.weight, d[next.v]);
}
}
} static void creatGraph() {
Scanner sc = new Scanner(System.in);
V = sc.nextInt();
E = sc.nextInt();
Edges = new ArrayList[V];
for (int i = 0; i < V; i++) {
Edges[i] = new ArrayList<Edge>();
}
for (int i = 0; i < E; i++) {
int u = sc.nextInt();
int v = sc.nextInt();
int w = sc.nextInt();
Edges[u].add(new Edge(v, w));
Edges[v].add(new Edge(u, w));
}
for (ArrayList<Edge> i : Edges) {
System.out.println(i);
}
}
} class Edge {
int v;
int weight; public Edge(int v, int weight) {
this.v = v;
this.weight = weight;
} @Override
public String toString() {
return "Edge{" +
"v=" + v +
", weight=" + weight +
'}';
}
}