Algorithm/์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ณต๋ถ€

[์•Œ๊ณ ๋ฆฌ์ฆ˜] ๋‹ค์ต์ŠคํŠธ๋ผ(Dijkstra) ์ตœ๋‹จ ๊ฒฝ๋กœ ์•Œ๊ณ ๋ฆฌ์ฆ˜

meeeeejin 2021. 3. 30. 17:09

๋ชฉ์ฐจ

  • ๋‹ค์ต์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์†Œ๊ฐœ
  • ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋™์ž‘ ๊ณผ์ •
  • ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ตฌํ˜„(ํŒŒ์ด์ฌ)

 

 

 

๋‹ค์ต์ŠคํŠธ๋ผ(Dijkstra) ์ตœ๋‹จ ๊ฒฝ๋กœ ์•Œ๊ณ ๋ฆฌ์ฆ˜

  • ํŠน์ • ์ •์ ์—์„œ ์ถœ๋ฐœํ•˜์—ฌ ๋‹ค๋ฅธ ๋ชจ๋“  ๋…ธ๋“œ๋กœ ๊ฐ€๋Š” ์ตœ๋‹จ ๊ฒฝ๋กœ ๊ณ„์‚ฐ
  • Single-Source Shortest Paths ๋ฌธ์ œ์— ์‚ฌ์šฉ๋  ์ˆ˜ ์žˆ์Œ
  • ๋งค ์ƒํ™ฉ์—์„œ ๊ฐ€์žฅ ๋น„์šฉ์ด ์ ์€ ๋…ธ๋“œ ์„ ํƒ์„ ๋ฐ˜๋ณต(๊ทธ๋ฆฌ๋”” ์•Œ๊ณ ๋ฆฌ์ฆ˜)

 

 

 

 

์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋™์ž‘ ๊ณผ์ •

  1. ์ถœ๋ฐœ ์ •์  ์„ ํƒ
  2. ์ตœ๋‹จ ๊ฑฐ๋ฆฌ ํ…Œ์ด๋ธ”์„ INF๋กœ ์ดˆ๊ธฐํ™”
  3. ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ์ •์  ์ค‘์—์„œ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๊ฐ€ ๊ฐ€์žฅ ์งง์€ ์ •์  ์„ ํƒ
  4. ํ•ด๋‹น ์ •์ ์„ ๊ฑฐ์ณ ๋‹ค๋ฅธ ์ •์ ์œผ๋กœ ๊ฐ€๋Š” ๋น„์šฉ์„ ๊ณ„์‚ฐํ•˜์—ฌ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ ํ…Œ์ด๋ธ” ๊ฐฑ์‹ 
  5. 3~4๋ฒˆ ๊ณผ์ • ๋ฐ˜๋ณต

 

 

 

 

 

 

์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ตฌํ˜„

๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ์ •์  ์ค‘์— ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๊ฐ€ ๊ฐ€์žฅ ์งง์€ ์ •์ ์„ ๋น ๋ฅด๊ฒŒ ์ฐพ๊ธฐ ์œ„ํ•ด ์šฐ์„ ์ˆœ์œ„ ํ ์‚ฌ์šฉ

import heapq
import sys
input = sys.stdin.readline
INF = int(1e9)

# ์ •์ ์˜ ๊ฐœ์ˆ˜, ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜ ์ž…๋ ฅ
n, m = map(int, input().split())
# ์‹œ์ž‘ ์ •์  ์ž…๋ ฅ
start = int(input())
# ์ธ์ ‘ ๋ฆฌ์ŠคํŠธ ์ƒ์„ฑ
graph = [[] for i in range(n + 1)]
# ์ตœ๋‹จ ๊ฑฐ๋ฆฌ ํ…Œ์ด๋ธ” ์ดˆ๊ธฐํ™”
distance = [INF] * (n + 1)

# ์ธ์ ‘ ๋ฆฌ์ŠคํŠธ ์ดˆ๊ธฐํ™”
for _ in range(m):
    i, j, c = map(int, input().split())
    graph[i].append((j, c)) # ์ •์  i์—์„œ ์ •์  j๋กœ ๊ฐ€๋Š” ๋น„์šฉ c

def dijkstra(start):
    q = []
    heapq.heappush(q, (0, start))   # ์‹œ์ž‘ ์ •์  ์‚ฝ์ž…
    distance[start] = 0
    while q:
        # ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๊ฐ€ ์ตœ์†Œ์ธ ์ •์ ์˜ ์ •๋ณด ๊บผ๋‚ด๊ธฐ
        dist, now = heapq.heappop(q)
        # ์ด๋ฏธ ๋ฐฉ๋ฌธํ•œ ์ •์ ์ธ์ง€ ํ™•์ธ
        if distance[now] < dist:
            continue
        # ํ˜„์žฌ ์ •์ ๊ณผ ์ธ์ ‘ํ•œ ์ •์  ํ™•์ธ
        for x in graph[now]:
            new_dist = dist + x[1]
            # ํ˜„์žฌ ์ •์ ์„ ๊ฑฐ์ณ๊ฐ€๋Š”๊ฒŒ ๊ฑฐ๋ฆฌ๊ฐ€ ๋” ์งง์„ ๊ฒฝ์šฐ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ ํ…Œ์ด๋ธ” ๊ฐฑ์‹ 
            if new_dist < distance[x[0]]:
                distance[x[0]] = new_dist
                heapq.heappush(q, (new_dist, x[0]))

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

# ์ตœ๋‹จ ๊ฑฐ๋ฆฌ ํ…Œ์ด๋ธ” ์ถœ๋ ฅ
for i in range(1, n + 1):
    # ๋„๋‹ฌํ•  ์ˆ˜ ์—†๋Š” ๊ฒฝ์šฐ INF ์ถœ๋ ฅ
    if distance[i] == INF:
        print("INF", end=" ")
    else:
        print(distance[i], end=" ")

 

์œ„์™€ ๊ฐ™์€ ๊ทธ๋ž˜ํ”„๋ฅผ ์ž…๋ ฅ์œผ๋กœ ๋„ฃ์„ ๊ฒฝ์šฐ 0 5 4 2 1 ์ถœ๋ ฅ

 

 

 

 

์ฐธ๊ณ 

 

 

 

 

 

728x90