본문 바로가기
Algorithm(알고리즘)/Java

[Java][백준 1753][그래프, 다익스트라] 최단 경로

by Jun_N 2021. 3. 23.

문제

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

 


문제 풀이

 

이 문제는 다익스트라 알고리즘을 알아야 풀 수 있는 문제이다.

하나의 정점에서 하나의 정점까지 가는 최단 거리들을 구하면 되는 문제이고 방법은 방문처리로 구하는 방법과 우선순위 큐로 구하는 방법이 있다.

 

0. 간선과 정점의 개수가 많아서 LinkedList를 사용해서 풀었다. 

1.  시작하는 distance의 거리를 0으로 초기화하고 시작한다.

2.  방문한 적이 없고 가장 짧은 거리를 찾아 그 값과 index값을 저장한다. (=> 이는 우선순위 큐를 사용하면 대체 가능하다)

3. 그 짧은 거리로 통해서 가는 정점을 거쳐서 가는 길들을 업데이트 해준다.

4. 모든 정점을 방문하면 종료. (혹은 end 포인트까지) 

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

// 다익스트라 + PQ 
public class BOJ_G5_1753_최단경로 {
	static class Node {
		int s, e;

		public Node(int s, int e) {
			super();
			this.s = s;
			this.e = e;
		}

	}

	static int V, E;
	static LinkedList<Node>[] adjList;
	static PriorityQueue<Node> pQueue = new PriorityQueue<Node>(new Comparator<Node>() {

		@Override
		public int compare(Node o1, Node o2) {
			return o1.s - o2.s;
		}

	});

	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());
		int start = Integer.parseInt(br.readLine());

		adjList = new LinkedList[V + 1];
		int[] distance = new int[V + 1];
		Arrays.fill(distance, Integer.MAX_VALUE);

		for (int i = 1; i <= V; i++) {
			adjList[i] = new LinkedList<Node>();
		}

		int u, v, w;
		for (int i = 0; i < E; i++) {
			st = new StringTokenizer(br.readLine(), " ");
			u = Integer.parseInt(st.nextToken());
			v = Integer.parseInt(st.nextToken());
			w = Integer.parseInt(st.nextToken());
			adjList[u].add(new Node(v, w));
		}
		distance[start] = 0;

		// 일반
		boolean[] visit = new boolean[V + 1];
		int min, cur = 0;
		for (int i = 1; i <= V; i++) {
			min = Integer.MAX_VALUE;
			for (int j = 1; j <= V; j++) {
				if (!visit[j] && distance[j] < min) {
					min = distance[j];
					cur = j;
				}
			}
			visit[cur] = true;
			for (Node next : adjList[cur]) {
				if (!visit[next.s] && min + next.e < distance[next.s]) {
					distance[next.s] = min + next.e;
				}
			}
		}

		// 우선순위 Queue 사용
//		pQueue.offer(new Node(0, start));
//		while (!pQueue.isEmpty()) {
//			Node cur = pQueue.poll();
//			for (Node next : adjList[cur.e]) {
//				if (distance[next.s] > cur.s + next.e) {
//					distance[next.s] = cur.s + next.e;
//					pQueue.offer(new Node(distance[next.s], next.s));
//				}
//			}
//		}

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

	}

}