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

【模板】单源最短路1

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

import java.util.Scanner;
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别

        String s = in.nextLine();
        String[] first = s.split(" ");
        int a = Integer.parseInt(first[0]);
        int b = Integer.parseInt(first[1]);
        int[][] dataRes = new int[5001][5001];
        for (int i = 0; i < b; i++) {
            String next = in.nextLine();
            String[] split = next.split(" ");
            dataRes[Integer.parseInt(split[0])][Integer.parseInt(split[1])] = 1;
            dataRes[Integer.parseInt(split[1])][Integer.parseInt(split[0])] = 1;
        }

        int[] length = new int[5001];
        Arrays.fill(length, 5001);
    
        for (int i = 1; i <= 5000; i++) {
            if (dataRes[1][i] != 0) {
                length[i] = 1;
            }
        }

        boolean[] visit = new boolean[5001];
        visit[1] = true;
        for (int i = 1; i < 5000; i++) {
            int key = 0;
           int min = 5001;
            for (int index = 1; index <= 5000; index++) {
                if (!visit[index] && length[index] < min) {
                    key = index;
                    min = length[index];
                }
            }
            if(key == 0) {
                break;
            }
            visit[key] = true;
            for (int j = 1; j <= 5000; j++) {
                if ( dataRes[key][j] != 0 && length[j]  > min + 1 ) {
                    length[j] = length[key] + 1;
                }
            }
        }
        System.out.println(length[a] > 5000 ? -1 : length[a]);
    }

}

全部评论

相关推荐

牛客84809583...:举报了
点赞 评论 收藏
分享
uu们,拒offer时hr很生气怎么办我哭死
爱睡觉的冰箱哥:人家回收你的offer,或者oc后没给你发offer的时候可不会愧疚你,所以你拒了也没必要愧疚他。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务