Skip to content

Commit eefa156

Browse files
committed
[PGS] 여행경로 / Level 2 / 50분 / 실패
1 parent d3ecea9 commit eefa156

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
def dfs(graph, start, path):
2+
while start in graph and graph[start]: # 시작점이 그래프에 있는지 확인하고, 도착지가 있는지 확인
3+
next_dest = graph[start].pop(0) # 알파벳 순으로 정렬되어 있으므로 첫 번째 경로를 선택
4+
dfs(graph, next_dest, path) # 재귀적으로 다음 도착지에서 다시 탐색
5+
path.append(start) # 더 이상 갈 곳이 없으면 현재 위치를 경로에 추가
6+
7+
def solution(tickets):
8+
# 그래프 초기화
9+
graph = {}
10+
for u, v in tickets: # 주어진 티켓 정보로 그래프 생성
11+
if u in graph:
12+
graph[u].append(v)
13+
else:
14+
graph[u] = [v]
15+
16+
# 각 출발지의 도착지 리스트를 알파벳 순으로 정렬 (문제 조건에 있음)
17+
for key in graph.keys():
18+
graph[key].sort()
19+
20+
path = [] # 최종 경로를 저장할 리스트
21+
dfs(graph, "ICN", path) # "ICN"에서 무조건 시작해야 함 -> ICN부터 DFS ㅇ탐색
22+
return path[::-1] # 경로를 역순으로 반환

0 commit comments

Comments
 (0)