1+ """
2+ 시작 = 1
3+ if 시작 ~ # 노드(N개) 까지의 최단 거리 <= K : 배달 가능True
4+ 다익스트라
5+ """
6+ import heapq
7+ INF = 2001
8+
9+ def dikstra (graph , distance , start ) :
10+ #2. distance 초기화 : (0,start)로 초기화 / q에 (0,start 넣기)
11+ q = []
12+ distance [start ] = 0
13+ heapq .heappush (q ,(0 ,start ))
14+ #3. q에서 최단 거리(start -> X) & 방문x 노드 선택
15+ while q :
16+ dist , now = heapq .heappop (q ) # A->X
17+ if distance [now ] < dist : # 방문 완료
18+ continue
19+ #4. Cost(X->B)계산 + Cost(A->X) < Cost(A->B) => distance 업데이트 + q에 넣기
20+ # graph 인접 간선(i[1]) , dist, 현distance[B]
21+ for i in graph [now ]: # i = (b,c)....
22+ cost = dist + i [1 ]
23+ if cost < distance [i [0 ]] :
24+ distance [i [0 ]] = cost
25+ heapq .heappush (q ,(cost ,i [0 ]))
26+ return distance
27+
28+ def solution (N , road , K ):
29+ # input
30+ graph = [[] for _ in range (N + 1 )]
31+ distance = [INF ]* (N + 1 ) # 최단거리 그래프
32+
33+ #0 그래프 필드 정의 a : [(b,c)...] #양방향
34+ road .sort ()
35+ for r in road :
36+ a = r [0 ] ; b = r [1 ] ; c = r [2 ]
37+ graph [a ].append ([b ,c ])
38+ graph [b ].append ([a ,c ])
39+
40+ # 다익스트라
41+ distance = dikstra (graph ,distance , 1 )
42+
43+ # 거리 < K 인 마을 개수
44+ count = 0
45+ for city in range (1 , N + 1 ) :
46+ if distance [city ] <= K :
47+ count += 1
48+ return count
49+
0 commit comments