@@ -655,6 +655,104 @@ int main() {
655
655
656
656
### Java
657
657
658
+ ``` Java
659
+
660
+ import java.util.* ;
661
+
662
+ class Edge {
663
+ int to; // 邻接顶点
664
+ int val; // 边的权重
665
+
666
+ Edge (int to , int val ) {
667
+ this . to = to;
668
+ this . val = val;
669
+ }
670
+ }
671
+
672
+ class MyComparison implements Comparator<Pair<Integer , Integer > > {
673
+ @Override
674
+ public int compare (Pair<Integer , Integer > lhs , Pair<Integer , Integer > rhs ) {
675
+ return Integer . compare(lhs. second, rhs. second);
676
+ }
677
+ }
678
+
679
+ class Pair <U, V> {
680
+ public final U first;
681
+ public final V second;
682
+
683
+ public Pair (U first , V second ) {
684
+ this . first = first;
685
+ this . second = second;
686
+ }
687
+ }
688
+
689
+ public class Main {
690
+ public static void main (String [] args ) {
691
+ Scanner scanner = new Scanner (System . in);
692
+ int n = scanner. nextInt();
693
+ int m = scanner. nextInt();
694
+
695
+ List<List<Edge > > grid = new ArrayList<> (n + 1 );
696
+ for (int i = 0 ; i <= n; i++ ) {
697
+ grid. add(new ArrayList<> ());
698
+ }
699
+
700
+ for (int i = 0 ; i < m; i++ ) {
701
+ int p1 = scanner. nextInt();
702
+ int p2 = scanner. nextInt();
703
+ int val = scanner. nextInt();
704
+ grid. get(p1). add(new Edge (p2, val));
705
+ }
706
+
707
+ int start = 1 ; // 起点
708
+ int end = n; // 终点
709
+
710
+ // 存储从源点到每个节点的最短距离
711
+ int [] minDist = new int [n + 1 ];
712
+ Arrays . fill(minDist, Integer . MAX_VALUE );
713
+
714
+ // 记录顶点是否被访问过
715
+ boolean [] visited = new boolean [n + 1 ];
716
+
717
+ // 优先队列中存放 Pair<节点,源点到该节点的权值>
718
+ PriorityQueue<Pair<Integer , Integer > > pq = new PriorityQueue<> (new MyComparison ());
719
+
720
+ // 初始化队列,源点到源点的距离为0,所以初始为0
721
+ pq. add(new Pair<> (start, 0 ));
722
+
723
+ minDist[start] = 0 ; // 起始点到自身的距离为0
724
+
725
+ while (! pq. isEmpty()) {
726
+ // 1. 第一步,选源点到哪个节点近且该节点未被访问过(通过优先级队列来实现)
727
+ // <节点, 源点到该节点的距离>
728
+ Pair<Integer , Integer > cur = pq. poll();
729
+
730
+ if (visited[cur. first]) continue ;
731
+
732
+ // 2. 第二步,该最近节点被标记访问过
733
+ visited[cur. first] = true ;
734
+
735
+ // 3. 第三步,更新非访问节点到源点的距离(即更新minDist数组)
736
+ for (Edge edge : grid. get(cur. first)) { // 遍历 cur指向的节点,cur指向的节点为 edge
737
+ // cur指向的节点edge.to,这条边的权值为 edge.val
738
+ if (! visited[edge. to] && minDist[cur. first] + edge. val < minDist[edge. to]) { // 更新minDist
739
+ minDist[edge. to] = minDist[cur. first] + edge. val;
740
+ pq. add(new Pair<> (edge. to, minDist[edge. to]));
741
+ }
742
+ }
743
+ }
744
+
745
+ if (minDist[end] == Integer . MAX_VALUE ) {
746
+ System . out. println(- 1 ); // 不能到达终点
747
+ } else {
748
+ System . out. println(minDist[end]); // 到达终点最短路径
749
+ }
750
+ }
751
+ }
752
+
753
+ ```
754
+
755
+
658
756
### Python
659
757
660
758
### Go
0 commit comments