Post

Dijikstra

🙋‍♂️ 들어가며

이번 시간에는 dijikstra를 배워보자

우선 이를 이해하기 위해서는 Priority Queue의 선행학습이 되어있어야할 것이다.

모른다면 이전의 Pritority Queue 관련 글을 보고 오자

dijikstra는 최소비용을 구할 때 많이 쓰인다.

Desktop View

위 그림을 토대로 아래에 구현해보자

✅ 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;

import java.util.Arrays;

// dijikstra
import java.util.PriorityQueue;
import java.util.ArrayList;
import java.util.List;

public class Main {
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		int N = 5;
		
		// 1. 그래프 생성
		List<int[]>[] graph = new ArrayList[N+1];
		for (int i = 1; i < N+1; i++) {
			graph[i] = new ArrayList<>();
		}
		
		// 2. 간선 추가 (to, cost)
		graph[1].add(new int[] {2, 2});
		graph[1].add(new int[] {3, 5});
		graph[2].add(new int[] {3, 1});
		graph[2].add(new int[] {4, 2});
		graph[3].add(new int[] {5, 3});
		
		// 3. 거리값 초기화
		int[] dist = new int[N+1];
		for (int i = 1; i < N+1; i++) {
			dist[i] = Integer.MAX_VALUE;
		}
		
		// 4. PQ (거리기준 정렬)
		PriorityQueue<int[]> pq = new PriorityQueue<> (
				(a,b) -> a[1] - b[1] 
		);
		
		// 5. 시작점은 0
		dist[1] = 0;

		// 6. 초기값 삽입 (노드, 거리)
		pq.offer(new int[] {1, 0});
		
		// 7. 탐색
		while (!pq.isEmpty()) {
			int[] cur = pq.poll();
			int cur_node = cur[0];
			int cur_cost = cur[1];
			
			if (cur_cost > dist[cur_node]) continue;
			
			for (int[] next : graph[cur_node]) {
				int next_node = next[0];
				int next_cost = cur_cost + next[1];
				
				if (next_cost < dist[next_node]) {
					dist[next_node] = next_cost;
					pq.offer(new int[] {next_node, next_cost});
				}
				
			}
			
		}
		
		// 8. 결과 출력
		for (int i = 1; i < N+1; i++) {
			System.out.println(i + " " + dist[i]);
		}
		
		
	}
}
This post is licensed under CC BY 4.0 by the author.

Trending Tags

도움이 필요하면
나를 눌러 구리🐻
챗봇
너굴
bot
어서와 구리 ʕ ·ᴥ·ʔ
무엇이 필요하셔 구리?

Trending Tags

도움이 필요하면
나를 눌러 구리🐻
챗봇
너굴
bot
어서와 구리 ʕ ·ᴥ·ʔ
무엇이 필요하셔 구리?