Post

Dijikstra

๐Ÿ™‹โ€โ™‚๏ธ ๋“ค์–ด๊ฐ€๋ฉฐ

์ด๋ฒˆ ์‹œ๊ฐ„์—๋Š” dijikstra๋ฅผ ๋ฐฐ์›Œ๋ณด์ž

์šฐ์„  ์ด๋ฅผ ์ดํ•ดํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” Priority Queue์˜ ์„ ํ–‰ํ•™์Šต์ด ๋˜์–ด์žˆ์–ด์•ผํ•  ๊ฒƒ์ด๋‹ค.

๋ชจ๋ฅธ๋‹ค๋ฉด ์ด์ „์˜ Pritority Queue ๊ด€๋ จ ๊ธ€์„ ๋ณด๊ณ  ์˜ค์ž

dijikstra๋Š” ์ตœ์†Œ๋น„์šฉ์„ ๊ตฌํ•  ๋•Œ ๋งŽ์ด ์“ฐ์ธ๋‹ค.

์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œ ํ’€์ด ์ฐธ๊ณ  ๋‹ค์ด์–ด๊ทธ๋žจ

์œ„ ๊ทธ๋ฆผ์„ ํ† ๋Œ€๋กœ ์•„๋ž˜์— ๊ตฌํ˜„ํ•ด๋ณด์ž

โœ… ์ฝ”๋“œ

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. graph ์ƒ์„ฑ
		List<int[]>[] graph = new ArrayList[N+1];
		for (int i = 1; i < N+1; i++) {
			graph[i] = new ArrayList<>();
		}
		
		// 2. ๊ฐ’ ๋Œ€์ž…
		graph[1].add(new int[] {2, 2});
		graph[1].add(new int[] {3, 5});
		graph[2].add(new int[] {4, 2});
		graph[2].add(new int[] {3, 1});
		graph[3].add(new int[] {5, 3});
		
		// 3. dist ๋ฐฐ์—ด ์ดˆ๊ธฐํ™”
		int[] dist = new int[N+1];
		for (int i = 1; i < N+1; i++) {
			dist[i] = Integer.MAX_VALUE;
		}
		
		// 4. ์‹œ์ž‘์ ์˜ ๋น„์šฉ์€ 0
		dist[1] = 0;
		
		// 5. pq -> ๋น„์šฉ asc
		PriorityQueue<int[]> pq = new PriorityQueue<> (
				(a,b) -> a[1] - b[1]
		);
		
		// 6. ์ดˆ๊ธฐ๊ฐ’ ์‚ฝ์ž…
		pq.offer(new int[] {1, 0});
		
		// 7. ํƒ์ƒ‰
		while (!pq.isEmpty()) {
			int[] cur_pos = pq.poll();
			int cur_node =cur_pos[0];
			int cur_cost = cur_pos[1];
			
			// 7-1. ํ˜„์žฌ ๋น„์šฉ์ด dist๋ณด๋‹ค ํฌ๋ฉด skip
			if (cur_cost > dist[cur_node]) continue;
			
			// 7-2. ์ž‘๋‹ค๋ฉด
			for (int[] next : graph[cur_node]) {
				int next_node = next[0];
				int next_cost = cur_cost + next[1];
				
				if (dist[next_node] > next_cost) {
					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(dist[i]);
		}
		
	}
}
This post is licensed under CC BY 4.0 by the author.

Trending Tags