카테고리 없음

Dijkstra: Shortest Reach 2

hyunmin43240 2025. 5. 5. 17:05

https://www.hackerrank.com/challenges/dijkstrashortreach/problem

 

Dijkstra: Shortest Reach 2 | HackerRank

Learn to use Dijkstra's shortest path algorithm !

www.hackerrank.com

 public static List<Integer> shortestReach(int n, List<List<Integer>> edges, int s) {
    // Write your code here
     List<List<int[]>> graph = new ArrayList<>();
    for (int i = 0; i <= n; i++) {
        graph.add(new ArrayList<>());
    }

    // Build adjacency list (undirected)
    for (List<Integer> edge : edges) {
        int u = edge.get(0);
        int v = edge.get(1);
        int w = edge.get(2);
        graph.get(u).add(new int[]{v, w});
        graph.get(v).add(new int[]{u, w});
    }

    int[] dist = new int[n + 1];
    Arrays.fill(dist, Integer.MAX_VALUE);
    dist[s] = 0;

    PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[1]));
    pq.offer(new int[]{s, 0});

    boolean[] visited = new boolean[n + 1];

    while (!pq.isEmpty()) {
        int[] curr = pq.poll();
        int u = curr[0];
        int d = curr[1];

        if (visited[u]) continue;
        visited[u] = true;

        for (int[] neighbor : graph.get(u)) {
            int v = neighbor[0];
            int weight = neighbor[1];

            if (!visited[v] && dist[u] + weight < dist[v]) {
                dist[v] = dist[u] + weight;
                pq.offer(new int[]{v, dist[v]});
            }
        }
    }

    List<Integer> result = new ArrayList<>();
    for (int i = 1; i <= n; i++) {
        if (i == s) continue;
        result.add(dist[i] == Integer.MAX_VALUE ? -1 : dist[i]);
    }

    return result;
}
}