Dijkstra Algorithm

์ตœ๋‹จ ๊ฒฝ๋กœ

์ตœ๋‹จ ๊ฒฝ๋กœ ์ •์˜

: ๊ฐ„์„ ์˜ ๊ฐ€์ค‘์น˜๊ฐ€ ์žˆ๋Š” ๊ทธ๋ž˜ํ”„์—์„œ ๋‘ ์ •์  ์‚ฌ์ด์˜ ๊ฒฝ๋กœ๋“ค ์ค‘์— ๊ฐ„์„ ์˜ ๊ฐ€์ค‘์น˜์˜ ํ•ฉ์ด ์ตœ์†Œ์ธ ๊ฒฝ๋กœ

ํ•˜๋‚˜์˜ ์‹œ์ž‘ ์ •์ ์—์„œ ๋ ์ •์ ๊นŒ์ง€์˜ ์ตœ๋‹จ ๊ฒฝ๋กœ (one to all)

  • ๋‹ค์ต์ŠคํŠธ๋ผ (dijkstra) ์•Œ๊ณ ๋ฆฌ์ฆ˜

    • ์Œ์˜ ๊ฐ€์ค‘์น˜๋ฅผ ํ—ˆ์šฉํ•˜์ง€ ์•Š์Œ

  • ๋ฒจ๋งŒ-ํฌ๋“œ (Bellman-Ford) ์•Œ๊ณ ๋ฆฌ์ฆ˜

    • ์Œ์˜ ๊ฐ€์ค‘์น˜ ํ—ˆ์šฉ

๋ชจ๋“  ์ •์ ๋“ค์— ๋Œ€ํ•œ ์ตœ๋‹จ ๊ฒฝ๋กœ

  • ํ”Œ๋กœ์ด๋“œ-์›Œ์ƒฌ (Floyd-Warshall) ์•Œ๊ณ ๋ฆฌ์ฆ˜

Dijkstra Algorithm

์‹œ์ž‘ ์ •์ ์—์„œ ๊ฑฐ๋ฆฌ๊ฐ€ ์ตœ์†Œ์ธ ์ •์ ์„ ์„ ํƒํ•ด ๋‚˜๊ฐ€๋ฉด์„œ ์ตœ๋‹จ ๊ฒฝ๋กœ๋ฅผ ๊ตฌํ•˜๋Š” ๋ฐฉ์‹

  • ์‹œ์ž‘ ์ •์  (s)์—์„œ ๋ ์ •์  (t) ๊นŒ์ง€์˜ ์ตœ๋‹จ ๊ฒฝ๋กœ์— ์ •์  x๊ฐ€ ์กด์žฌํ•œ๋‹ค

  • ์ด๋•Œ, ์ตœ๋‹จ ๊ฒฝ๋กœ๋Š” s์—์„œ x๊นŒ์ง€์˜ ์ตœ๋‹จ ๊ฒฝ๋กœ์™€ x ์—์„œ t ๊นŒ์ง€์˜ ์ตœ๋‹จ ๊ฒฝ๋กœ๋กœ ๊ตฌ์„ฑ๋œ๋‹ค

  • ํƒ์š• (greedy) ๊ธฐ๋ฒ•์„ ์‚ฌ์šฉํ•œ ์•Œ๊ณ ๋ฆฌ์ฆ˜์œผ๋กœ MST์˜ Prim Algorithm๊ณผ ์œ ์‚ฌํ•˜๋‹ค

  • ์ธ์ ‘ ํ–‰๋ ฌ ๊ทธ๋ž˜ํ”„์™€ ์‹œ์ž‘ ์ •์ ์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, ๋‹ค์ต์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์‚ฌ์šฉํ•˜๋ฉด ์‹œ์ž‘ ์ •์ ์—์„œ ๋ชจ๋“  ์ •์ ์œผ๋กœ ๊ฐ€๋Š” ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค

์‹œ๊ฐ„ ๋ณต์žก๋„

: O(logN)

๊ตฌํ˜„ ํ•ด๋ณด๊ธฐ

Dijkstra + ์ธ์ ‘๋ฆฌ์ŠคํŠธ

"""
6 11
0 1 3
0 2 5
1 2 2
1 3 6
2 1 1
2 3 4
2 4 6
3 4 2
3 5 3
4 0 3
4 5 6

๊ฒฐ๊ณผ
[0, 3, 5, 9, 11, 12]
"""

# dist, selected ๋ฐฐ์—ด ์ค€๋น„
# ์‹œ์ž‘์  ์„ ํƒ
# ๋ชจ๋“  ์ •์ ์ด ์„ ํƒ๋  ๋•Œ ๊นŒ์ง€
# ์•„์ง ์„ ํƒ๋˜์ง€ ์•Š๊ณ  dist์˜ ๊ฐ’์ด ์ตœ์†Œ์ธ ์ •์  : u
# ์ •์  u์˜ ์ตœ๋‹จ๊ฑฐ๋ฆฌ ๊ฒฐ์ •
# ์ •์  u์— ์ธ์ ‘ํ•œ ์ •์ ์— ๋Œ€ํ•ด์„œ ๊ฐ„์„  ์™„ํ™”

V, E = map(int, input().split())
adj = {i:[] for i in range(V)}

for i in range(E):
    s, e, c = map(int, input().split())
    adj[s].append([e,c]) #๋ฐฉํ–ฅ ๊ทธ๋ž˜ํ”„๋ผ์„œ

INF = float('inf')
dist = [INF]*V
selected = [False]*V

dist[0] = 0
cnt = 0
while cnt <V:
    # dist๊ฐ€ ์ตœ์†Œ์ธ ์ •์  ์ฐพ๊ธฐ
    MIN = INF
    for i in range(V):
        if not selected[i] and dist[i] < MIN:
            MIN = dist[i]
            u = i
    # ๊ฒฐ์ •
    selected[u] = True
    cnt += 1

    # ๊ฐ„์„  ์™„ํ™”
    for w, cost in adj[u]: # ๋„์ฐฉ์ •์ , ๊ฐ€์ฆ์น˜
        if dist[w] > dist[u] + cost:
            dist[w] = dist[u] + cost
    
print(dist) # [0, 3, 5, 9, 11, 12]

Last updated