Skip to content

Commit

Permalink
44.py
Browse files Browse the repository at this point in the history
  • Loading branch information
huisuu committed Aug 24, 2024
1 parent 0e207d2 commit 5c588f3
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions HSKIM/41to50/44.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
from collections import deque

def solution(N, road, K):
distance = [float("inf")] * (N + 1)
answer = set()
graph = {start: {} for start in range(1, N + 1)} # key: 출발지, value: 도착지와 거리
distance[0] = 0

queue = deque()
queue.append([1, 1, 0])

# value 값에서 더 낮은 거리를 값으로 가지도록 함
for start, end, weight in road:
if end in graph[start]:
graph[start][end] = min(weight, graph[start][end])
graph[end][start] = min(weight, graph[start][end])
else:
graph[start][end] = weight
graph[end][start] = weight

while queue:
past, cur, cnt = queue.popleft()
answer.add(cur)

# 이전에 방문한 곳이 아니며 K 값 이내이면서 최단거리일 때 큐에 저장
for town in graph[cur]:
if town != past and cnt + graph[cur][town] <= K:
if cnt + graph[cur][town] < distance[town - 1]:
distance[town - 1] = cnt + graph[cur][town]
queue.append([cur, town, cnt + graph[cur][town]])


return len(answer)


N = 5
road = [[1,2,1],[2,3,3],[5,2,2],[1,4,2],[5,3,1],[5,4,2]]
K = 3
print(solution(N, road, K))

0 comments on commit 5c588f3

Please sign in to comment.