[백준] BOJ_1753 최단경로 JAVA

최진민·2021년 3월 26일
0

Algorithm_BOJ

목록 보기
71/92
post-thumbnail

BOJ_1753 최단 경로

문제

방향그래프가 주어지면 주어진 시작점에서 다른 모든 정점으로의 최단 경로를 구하는 프로그램을 작성하시오. 단, 모든 간선의 가중치는 10 이하의 자연수이다.


입력

첫째 줄에 정점의 개수 V와 간선의 개수 E가 주어진다. (1≤V≤20,000, 1≤E≤300,000) 모든 정점에는 1부터 V까지 번호가 매겨져 있다고 가정한다. 둘째 줄에는 시작 정점의 번호 K(1≤K≤V)가 주어진다. 셋째 줄부터 E개의 줄에 걸쳐 각 간선을 나타내는 세 개의 정수 (u, v, w)가 순서대로 주어진다. 이는 u에서 v로 가는 가중치 w인 간선이 존재한다는 뜻이다. u와 v는 서로 다르며 w는 10 이하의 자연수이다. 서로 다른 두 정점 사이에 여러 개의 간선이 존재할 수도 있음에 유의한다.


출력

첫째 줄부터 V개의 줄에 걸쳐, i번째 줄에 i번 정점으로의 최단 경로의 경로값을 출력한다. 시작점 자신은 0으로 출력하고, 경로가 존재하지 않는 경우에는 INF를 출력하면 된다.


예제 입&출력


소스코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    private static int v, e, start;
    private static List<Node>[] infoList;
    private static boolean[] visit;
    private static int[] dist;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        v = Integer.parseInt(st.nextToken());
        e = Integer.parseInt(st.nextToken());

        start = Integer.parseInt(br.readLine());

        infoList = new ArrayList[v + 1];
        for (int i = 0; i <= v; i++) {
            infoList[i] = new ArrayList<>();
        }
        visit = new boolean[v + 1];
        dist = new int[v + 1];
        Arrays.fill(dist, Integer.MAX_VALUE);

        for (int i = 0; i < e; i++) {
            st = new StringTokenizer(br.readLine());

            int u = Integer.parseInt(st.nextToken());
            int v = Integer.parseInt(st.nextToken());
            int cost = Integer.parseInt(st.nextToken());

            infoList[u].add(new Node(v, cost));
        }

        PriorityQueue<Node> pq = new PriorityQueue<>();
        pq.add(new Node(start, 0));
        dist[start] = 0;

        while (!pq.isEmpty()) {
            Node curNode = pq.poll();
            int cur = curNode.next;

            if (!visit[cur]) {
                visit[cur] = true;
            }

            for (Node nextNode : infoList[cur]) {
                if (dist[nextNode.next] > dist[cur] + nextNode.cost) {
                    dist[nextNode.next] = dist[cur] + nextNode.cost;
                    pq.add(new Node(nextNode.next, dist[nextNode.next]));
                }
            }
        }

        for (int i = 1; i <= v; i++) {
            if (dist[i] == Integer.MAX_VALUE) {
                System.out.println("INF");
            } else {
                System.out.println(dist[i]);
            }
        }
    }

    private static class Node implements Comparable<Node> {
        int next;
        int cost;

        public Node(int next, int cost) {
            this.next = next;
            this.cost = cost;
        }

        @Override
        public int compareTo(Node o) {
            return this.cost - o.cost;
        }
    }
}

Comment

  • 가중치가 있는 인접 리스트를 bfs를 이용하여 푸는 기본적인 최단 경로 문제(=다익스트라 알고리즘)
  • 알고리즘을 푸는 사람들은 대부분 아래와 같이 2가지 방법을 사용한다. 필자는 2번째를 사용했고 두 가지 모두 알아보자. 참고 블로그
    • 배열
    • 리스트 + 우선순위 큐

profile
열심히 해보자9999

0개의 댓글