MCPcopy Create free account
hub / github.com/Seogeurim/CS-study / BellmanFord

Class BellmanFord

contents/algorithm/code/BellmanFordTest.java:21–93  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

19}
20
21class BellmanFord {
22 private int N;
23 private ArrayList<Edge> edges;
24
25 private final static int INF = Integer.MAX_VALUE;
26 private int[] D;
27
28 public BellmanFord(int N) {
29 this.N = N;
30 edges = new ArrayList<>();
31 D = new int[N+1];
32 }
33
34 public void addEdge(int from, int to, int weight) {
35 edges.add(new Edge(from, to, weight));
36 }
37
38 public void printEdges() {
39 for (Edge edge : edges) System.out.println(edge);
40 }
41
42 public void getShortestDistance(int S) {
43 /* init */
44 for (int i = 1; i <= N; i++) {
45 if (i != S) D[i] = INF;
46 }
47
48 /* Bellman-Ford */
49 boolean negCycle = false;
50 for (int i = 1; i <= N; i++) {
51 for (Edge edge : edges) {
52 int from = edge.from;
53 int to = edge.to;
54 int weight = edge.weight;
55 if (D[from] != INF && D[to] > D[from] + weight) {
56 if (i == N) {
57 negCycle = true;
58 break;
59 }
60 D[to] = D[from] + weight;
61 }
62 }
63 }
64
65 if (negCycle) System.out.println("음의 사이클이 존재합니다.");
66 else printDistance();
67 }
68
69 private void printDistance() {
70 for (int i = 1; i <= N; i++) {
71 if (D[i] == INF) System.out.print("∞ ");
72 else System.out.print(D[i] + " ");
73 }
74 System.out.println();
75 }
76
77 static class Edge {
78 private int from;

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected