ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90

 

๐ŸŒ Summer/Winter Coding(~2018)

 

๋ฌธ์ œ

https://programmers.co.kr/learn/courses/30/lessons/12978

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ๋ฐฐ๋‹ฌ

5 [[1,2,1],[2,3,3],[5,2,2],[1,4,2],[5,3,1],[5,4,2]] 3 4 6 [[1,2,1],[1,3,2],[2,3,2],[3,4,3],[3,5,2],[3,5,3],[5,6,1]] 4 4

programmers.co.kr

 

 

thinking

์ตœ๋‹จ๊ฑฐ๋ฆฌ์ด๊ธฐ ๋•Œ๋ฌธ์— ๋‹ค์ต์ŠคํŠธ๋ผ๋ฅผ ์‚ฌ์šฉํ–ˆ๋‹ค

๋‚˜๋™๋นˆ๋‹˜์˜ ๋ธ”๋กœ๊ทธ๋ฅผ ๋ณด๋ฉด ์ดํ•ด๊ฐ€ ์•„์ฃผ ์‰ฝ๋‹ค. ๊ตฟ !!!!!!

https://blog.naver.com/PostView.naver?blogId=ndb796&logNo=221234424646&redirect=Dlog&widgetTypeCall=true&directAccess=false 

 

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

๋‹ค์ต์ŠคํŠธ๋ผ(Dijkstra) ์•Œ๊ณ ๋ฆฌ์ฆ˜์€ ๋‹ค์ด๋‚˜๋ฏน ํ”„๋กœ๊ทธ๋ž˜๋ฐ์„ ํ™œ์šฉํ•œ ๋Œ€ํ‘œ์ ์ธ ์ตœ๋‹จ ๊ฒฝ๋กœ(Shortest Path) ํƒ...

blog.naver.com

 

 

์ฝ”๋“œ

import heapq

def dijkstra(dist,adj):
    # ์ถœ๋ฐœ๋…ธ๋“œ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๊ฐ ๋…ธ๋“œ๋“ค์˜ ์ตœ์†Œ๋น„์šฉ ํƒ์ƒ‰
    heap = []
    heapq.heappush(heap, [0,1])  # ๊ฑฐ๋ฆฌ,๋…ธ๋“œ
    while heap:
        cost, node = heapq.heappop(heap)
        for c,n in adj[node]:
            if cost+c < dist[n]:
                dist[n] = cost+c
                heapq.heappush(heap, [cost+c,n])


def solution(N, road, K):
    dist = [float('inf')]*(N+1)  # dist ๋ฐฐ์—ด ๋งŒ๋“ค๊ณ  ์ตœ์†Œ๊ฑฐ๋ฆฌ ๊ฐฑ์‹ ํ• ๊ฑฐ์ž„
    dist[1] = 0  # 1๋ฒˆ์€ ์ž๊ธฐ์ž์‹ ์ด๋‹ˆ๊นŒ ๊ฑฐ๋ฆฌ 0
    adj = [[] for _ in range(N+1)]  # ์ธ์ ‘๋…ธ๋“œ&๊ฑฐ๋ฆฌ ๊ธฐ๋กํ•  ๋ฐฐ์—ด
    for r in road:
        adj[r[0]].append([r[2],r[1]])
        adj[r[1]].append([r[2],r[0]])
    dijkstra(dist,adj)
    return len([i for i in dist if i <=K])

 

๋Œ“๊ธ€