@@ -352,6 +352,77 @@ SPFA(队列优化版Bellman_ford) 在理论上 时间复杂度更胜一筹
352352## 其他语言版本
353353
354354### Java
355+ ``` Java
356+ import java.util.* ;
357+
358+ public class Main {
359+
360+ // Define an inner class Edge
361+ static class Edge {
362+ int from;
363+ int to;
364+ int val;
365+ public Edge (int from , int to , int val ) {
366+ this . from = from;
367+ this . to = to;
368+ this . val = val;
369+ }
370+ }
371+
372+ public static void main (String [] args ) {
373+ // Input processing
374+ Scanner sc = new Scanner (System . in);
375+ int n = sc. nextInt();
376+ int m = sc. nextInt();
377+ List<List<Edge > > graph = new ArrayList<> ();
378+
379+ for (int i = 0 ; i <= n; i++ ) {
380+ graph. add(new ArrayList<> ());
381+ }
382+
383+ for (int i = 0 ; i < m; i++ ) {
384+ int from = sc. nextInt();
385+ int to = sc. nextInt();
386+ int val = sc. nextInt();
387+ graph. get(from). add(new Edge (from, to, val));
388+ }
389+
390+ // Declare the minDist array to record the minimum distance form current node to the original node
391+ int [] minDist = new int [n + 1 ];
392+ Arrays . fill(minDist, Integer . MAX_VALUE );
393+ minDist[1 ] = 0 ;
394+
395+ // Declare a queue to store the updated nodes instead of traversing all nodes each loop for more efficiency
396+ Queue<Integer > queue = new LinkedList<> ();
397+ queue. offer(1 );
398+
399+ // Declare a boolean array to record if the current node is in the queue to optimise the processing
400+ boolean [] isInQueue = new boolean [n + 1 ];
401+
402+ while (! queue. isEmpty()) {
403+ int curNode = queue. poll();
404+ isInQueue[curNode] = false ; // Represents the current node is not in the queue after being polled
405+ for (Edge edge : graph. get(curNode)) {
406+ if (minDist[edge. to] > minDist[edge. from] + edge. val) { // Start relaxing the edge
407+ minDist[edge. to] = minDist[edge. from] + edge. val;
408+ if (! isInQueue[edge. to]) { // Don't add the node if it's already in the queue
409+ queue. offer(edge. to);
410+ isInQueue[edge. to] = true ;
411+ }
412+ }
413+ }
414+ }
415+
416+ // Outcome printing
417+ if (minDist[n] == Integer . MAX_VALUE ) {
418+ System . out. println(" unconnected" );
419+ } else {
420+ System . out. println(minDist[n]);
421+ }
422+ }
423+ }
424+
425+ ```
355426
356427### Python
357428
0 commit comments