题解 | #【模板】单源最短路1#

【模板】单源最短路1

https://www.nowcoder.com/practice/f24504c9ff544f7c808f76693cc34af8

import java.io.*;
import java.util.*;

/**
 * @BelongsProject: GXUOJ
 * @Author: Ling xi_Li
 * @CreateTime: 2023-12-04 11-44
 * @Description: TODO 迪杰斯特拉+邻接表
 */

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));

        String[] nums = in.readLine().split(" ");
        int V = Integer.parseInt(nums[0]);
        int E = Integer.parseInt(nums[1]);

        //邻接表
        ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
        //初始化 5000个点(题目要求)
        for (int i = 0; i < 5000; i++) {
            graph.add(new ArrayList<>());
        }

        //初始化邻接表
        for (int i = 0; i < E; i++) {
            nums = in.readLine().split(" ");
            int begin = Integer.parseInt(nums[0]) - 1;
            int end = Integer.parseInt(nums[1]) - 1;

            graph.get(begin).add(end);
            graph.get(end).add(begin);
        }
        in.close();

        //状态数组
        boolean[] statue = new boolean[5000];
        Arrays.fill(statue, false);
        //路径距离数组
        int[] dist = new int[5000];
        Arrays.fill(dist, Integer.MAX_VALUE);
        dist[0] = 0;

	  //要实现比较器方法
        PriorityQueue<Integer> queue = new PriorityQueue<>(Comparator.comparingInt(e -> dist[e]));
        queue.add(0);

        while (!queue.isEmpty()) {
            int current = queue.poll();
            //如果已经访问过,跳过
            if (statue[current]) continue;
            statue[current] = true;

            ArrayList<Integer> list = graph.get(current);
            for (int i : list) {
                if (!statue[i] && dist[i] > dist[current] + 1) {
                    dist[i] = dist[current] + 1;
                    queue.add(i);
                }
            }
        }
        if (dist[V - 1] != Integer.MAX_VALUE) out.write(dist[V - 1] + "");
        else out.write("-1");
        out.close();
    }
}

全部评论

相关推荐

11-03 14:38
重庆大学 Java
AAA求offer教程:我手都抬起来了又揣裤兜了
点赞 评论 收藏
分享
头像
11-21 11:39
四川大学 Java
是红鸢啊:忘了还没结束,还有字节的5k 违约金
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务