Last active
June 27, 2022 22:33
-
-
Save bvolpato/8d7a41f2007a31db0790ab57a77682e3 to your computer and use it in GitHub Desktop.
Algorithm - Bellman-Ford
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
/** | |
* Bellman-Ford Java Implementation | |
*/ | |
public class BellmanFord { | |
public static void main(String[] args) { | |
Scanner sc = new Scanner(System.in); | |
while (true) { | |
int n = sc.nextInt(); | |
int m = sc.nextInt(); | |
if (n == 0 && m == 0) { | |
return; | |
} | |
float[][] D = new float[n][n]; | |
for (int i = 0; i < m; i++) { | |
int x = sc.nextInt(); | |
int y = sc.nextInt(); | |
float f = sc.nextFloat(); | |
D[x][y] = f; | |
D[y][x] = f; | |
} | |
float[] dist = new float[n]; | |
dist[0] = 0; | |
for (int i = 1; i < n; i++) { | |
dist[i] = -1; | |
} | |
for (int repeats = 0; repeats < n; repeats++) { | |
boolean updated = false; | |
for (int i = 0; i < n; i++) { | |
for (int j = 0; j < n; j++) { | |
if (D[i][j] > 0) { | |
float candidate = dist[i] + D[i][j]; | |
if (candidate < dist[j]) { | |
dist[j] = candidate; | |
updated = true; | |
} | |
} | |
} | |
} | |
if (!updated) { | |
break; | |
} | |
} | |
System.out.printf("%.4f\n", dist[n - 1]); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment