Skip to content

Commit 02cfb92

Browse files
committed
Solved week 6
1 parent 821c136 commit 02cfb92

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

이수빈/Week6_배달.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
from queue import PriorityQueue
2+
3+
4+
def making_graph(N, road):
5+
graph = {} # 주어진 마을과 도로의 모양을 나타냄 {1: {2: 1}}이면 1번 나라에서 2번 나라로 갈 때 1시간이 걸린다는 뜻
6+
distance = {} # 1번 마을로부터 떨어진 거리
7+
for i in range(N):
8+
graph[i + 1] = {}
9+
distance[i + 1] = float('inf')
10+
11+
for j in range(N):
12+
for x in range(len(road)):
13+
for y in range(len(road[x])):
14+
if road[x][0] == (j + 1):
15+
# 여러 개의 거리 중 걸리는 시간이 더 짧은 것을 선택하기 위한 조건
16+
if (road[x][1] not in graph[j + 1]) or (graph[j + 1][road[x][1]] > road[x][2]):
17+
graph[j + 1].update({road[x][1]: road[x][2]})
18+
# 방향이 없는 그래프이므로 반대 방향의 나라 기준에서도 거리 기재
19+
graph[road[x][1]].update({(j + 1): road[x][2]})
20+
return graph, distance
21+
22+
23+
def solution(N, road, K):
24+
priority_queue = PriorityQueue() # 맨 앞의 값을 효율적으로 얻기 위해 PriorityQueue 사용
25+
graph, distance = making_graph(N, road)
26+
distance[1] = 0 # 1번 나라는 자기 나라에 갈 때 걸리는 시간이 0시간
27+
priority_queue.put(1)
28+
while priority_queue.qsize() != 0: # priority_queue가 빌 때까지
29+
target_country = priority_queue.get() # 맨 앞의 나라 기준으로 살펴본다
30+
for key, value in graph[target_country].items():
31+
# 이미 저장된 시간보다 새로 들어온 시간이 더 오래 걸리면 스킵한다.
32+
if distance[key] < distance[target_country] + value:
33+
continue
34+
distance[key] = distance[target_country] + value
35+
priority_queue.put(key) # 전 나라와 연결된 나라를 queue에 넣어준다.
36+
37+
counter = 0
38+
for result in distance.values(): # 최종적으로 나온 시간들 중 K시간 이하인 것들의 개수를 구한다.
39+
if result <= K:
40+
counter += 1
41+
return counter

0 commit comments

Comments
 (0)