boj1753 - 최단경로(Java)

이상욱·2022년 11월 24일
0

알고리즘

목록 보기
7/18
post-thumbnail

문제 설명

문제
방향그래프가 주어지면 주어진 시작점에서 다른 모든 정점으로의 최단 경로를 구하는 프로그램을 작성하시오. 단, 모든 간선의 가중치는 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를 출력하면 된다.

문제 풀이

  1. 한 정점에서 한 정점으로의 최단 경로값을 구해야 하므로 다익스트라 알고리즘을 이용한다.
  2. dist배열을 만든 후 INF(Integer.MAX_VALUE)로 초기화 해준다.
  3. Node클래스를 만들어 time을 기준으로 오름차순 정렬한다.
  4. 경로 노드를 입력받아 리스트에 시작 노드 리스트에 끝 노드, 시간을 넣어준다.
  5. 입력받은 start에서 시작하여 각 정점에의 최단 거리를 dist배열에 갱신시켜준다.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

public class Main {
    static int V,E;
    static int start;

    static int[] dist;
    static boolean[] visit;
    static ArrayList<ArrayList<Node>> nodeList;
    public static void main(String[] args) throws Exception{

        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());
        dist = new int[V+1];
        Arrays.fill(dist,Integer.MAX_VALUE);
        visit = new boolean[V+1];
        nodeList = new ArrayList<>();


        for(int i = 0; i < V+1; i++){
            nodeList.add(new ArrayList<>());
        }

        for(int i = 0; i < E; i++){
            st = new StringTokenizer(br.readLine());
            int from = Integer.parseInt(st.nextToken());
            int to = Integer.parseInt(st.nextToken());
            int time = Integer.parseInt(st.nextToken());

            nodeList.get(from).add(new Node(to,time));
        }

        dijkstra(start);

        for(int i = 1; i <=V; i++){
            System.out.println(dist[i] == Integer.MAX_VALUE? "INF" : dist[i]);
        }

    }

    private static void dijkstra(int start) {
        dist[start] = 0;
        Node node = new Node(start,0);
        PriorityQueue<Node> pq = new PriorityQueue<>();

        pq.offer(node);

        while (!pq.isEmpty()){
            Node cur = pq.poll();
            int to = cur.to;
            int time = cur.time;

            if(visit[to]){
                continue;
            }

            visit[to] = true;
            ArrayList<Node> nextList = nodeList.get(to);

            for(int i = 0; i < nextList.size(); i++){
                Node tmp = nextList.get(i);
                if(dist[tmp.to] > dist[to] + tmp.time){
                    dist[tmp.to] = dist[to] + tmp.time;
                    pq.add(new Node(tmp.to,dist[tmp.to]));
                }
            }

        }
    }
}

class Node implements Comparable<Node>{
    int to;
    int time;

    Node(int to, int time){
        this.to = to;
        this.time = time;
    }
    @Override
    public int compareTo(Node n){
        return this.time - n.time;
    }


}
profile
항상 배우고 성장하는 안드로이드 개발자

0개의 댓글