@@ -392,6 +392,63 @@ Bellman_ford 是可以计算 负权值的单源最短路算法。
392
392
## 其他语言版本
393
393
394
394
### Java
395
+ ``` Java
396
+ public class Main {
397
+
398
+ // Define an inner class Edge
399
+ static class Edge {
400
+ int from;
401
+ int to;
402
+ int val;
403
+ public Edge (int from , int to , int val ) {
404
+ this . from = from;
405
+ this . to = to;
406
+ this . val = val;
407
+ }
408
+ }
409
+
410
+ public static void main (String [] args ) {
411
+ // Input processing
412
+ Scanner sc = new Scanner (System . in);
413
+ int n = sc. nextInt();
414
+ int m = sc. nextInt();
415
+ List<Edge > edges = new ArrayList<> ();
416
+
417
+ for (int i = 0 ; i < m; i++ ) {
418
+ int from = sc. nextInt();
419
+ int to = sc. nextInt();
420
+ int val = sc. nextInt();
421
+ edges. add(new Edge (from, to, val));
422
+ }
423
+
424
+ // Represents the minimum distance from the current node to the original node
425
+ int [] minDist = new int [n + 1 ];
426
+
427
+ // Initialize the minDist array
428
+ Arrays . fill(minDist, Integer . MAX_VALUE );
429
+ minDist[1 ] = 0 ;
430
+
431
+ // Starts the loop to relax all edges n - 1 times to update minDist array
432
+ for (int i = 1 ; i < n; i++ ) {
433
+
434
+ for (Edge edge : edges) {
435
+ // Updates the minDist array
436
+ if (minDist[edge. from] != Integer . MAX_VALUE && (minDist[edge. from] + edge. val) < minDist[edge. to]) {
437
+ minDist[edge. to] = minDist[edge. from] + edge. val;
438
+ }
439
+ }
440
+ }
441
+
442
+ // Outcome printing
443
+ if (minDist[n] == Integer . MAX_VALUE ) {
444
+ System . out. println(" unconnected" );
445
+ } else {
446
+ System . out. println(minDist[n]);
447
+ }
448
+ }
449
+ }
450
+
451
+ ```
395
452
396
453
### Python
397
454
0 commit comments