Question
문제 해설
- 방향그래프가 주어지면 주어진 시작점에서 다른 모든 정점으로의 최단 경로를 구하여라
- 단, 모든 간선의 가중치는 10 이하의 자연수
Solution
풀이 접근 방법
- 시작점부터 다른 모든 정점까지의 최단 경로
- 하나의 시작점 -> 다수의 도착지점까지의 최단 거리 => 다익스트라 / 벨만포드 알고리즘
- 모든 간선의 가중치는 10 이하의 자연수 -> 음수 없음
- => 다익스트라 알고리즘 사용
정답 코드
package com.baekjoon.graph;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class Main_1753 {
static class Node implements Comparable<Node> {
int idx, cost;
public Node(int end, int cost) {
this.idx = end;
this.cost = cost;
}
@Override
public int compareTo(Node o) {
return Integer.compare(this.cost, o.cost);
}
}
static int V;
static int INF = 987654321;
static LinkedList<Node>[] graph;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringBuilder answer = new StringBuilder();
StringTokenizer st = new StringTokenizer(br.readLine());
V = Integer.valueOf(st.nextToken());
int E = Integer.valueOf(st.nextToken());
int start = Integer.valueOf(br.readLine()) - 1;
graph = new LinkedList[V];
for (int i = 0; i < V; i++) {
graph[i] = new LinkedList<Node>();
}
while (E-- > 0) {
st = new StringTokenizer(br.readLine());
int u = Integer.valueOf(st.nextToken()) - 1;
int v = Integer.valueOf(st.nextToken()) - 1;
int w = Integer.valueOf(st.nextToken());
graph[u].add(new Node(v, w));
}
int[] dist = dijkstra(start);
for (int cost : dist) {
answer.append(cost == INF ? "INF" : cost).append("\n");
}
bw.write(answer.toString() + "\n");
bw.flush();
bw.close();
}
static int[] dijkstra(int start) {
int[] dist = new int[V];
boolean[] visited = new boolean[V];
PriorityQueue<Node> pq = new PriorityQueue<Node>();
Arrays.fill(dist, INF);
dist[start] = 0;
pq.add(new Node(start, 0));
while (!pq.isEmpty()) {
Node current = pq.poll();
int here = current.idx;
if (current.cost > dist[current.idx])
continue;
for (Node next : graph[here]) {
int nIdx = next.idx;
if (visited[nIdx])
continue;
if (dist[nIdx] > dist[here] + next.cost) {
dist[nIdx] = dist[here] + next.cost;
pq.add(new Node(nIdx, dist[nIdx]));
}
}
visited[here] = true;
}
return dist;
}
}