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

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

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

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

 

๋ฌธ์ œ ํ’€์ด

 ๋ฌธ์ œ ์กฐ๊ฑด์— ๋”ฐ๋ผ K ์‹œ๊ฐ„ ์ดํ•˜๋กœ ๋ฐฐ๋‹ฌ ๊ฐ€๋Šฅํ•œ ๋งˆ์„์—์„œ๋งŒ ์ฃผ๋ฌธ์„ ๋ฐ›์•„์•ผ ํ•œ๋‹ค. ์ด๋•Œ ์Œ์‹ ์ฃผ๋ฌธ์„ ๋ฐ›์„ ์ˆ˜ ์žˆ๋Š” ๋งˆ์„์˜ ๊ฐœ์ˆ˜๋ฅผ ๋ฐ˜ํ™˜ํ•˜์—ฌ์•ผ ํ•œ๋‹ค. ๋ชจ๋“  ๊ฒฝ์šฐ๋ฅผ `BFS`๋กœ ํƒ์ƒ‰ํ•˜๋Š” ๊ฒƒ์€ ๋น„ํšจ์œจ์ ์ด๋‹ค. ๋”ฐ๋ผ์„œ `๋‹ค์ต์ŠคํŠธ๋ผ`๋ฅผ ์ ์šฉํ•˜์—ฌ ํƒ์ƒ‰์„ ํ•˜๊ฒŒ ๋˜๋ฉด ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค.

 

์ฝ”๋“œ

from math import inf
from collections import deque


def solution(N, road, K):
    visited = [False] * (N + 1)
    dists = [inf] * (N + 1)
    dists[1] = 0
    q = deque([1])

    while q:
        parent = q.popleft()
        visited[parent] = True

        for node1, node2, dist in road:
            if node1 == parent or node2 == parent:
                target = node1

                if node1 == parent:
                    target = node2

                if dists[target] > dists[parent] + dist:
                    dists[target] = dists[parent] + dist
                    q.append(target)

    return sum(1 for d in dists if d <= K)

 

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€