728x90
반응형
https://school.programmers.co.kr/learn/courses/30/lessons/43164
문제 설명
주어진 항공권을 모두 이용하여 여행경로를 짜려고 합니다. 항상 "ICN" 공항에서 출발합니다.
항공권 정보가 담긴 2차원 배열 tickets가 매개변수로 주어질 때, 방문하는 공항 경로를 배열에 담아 return 하도록 solution 함수를 작성해주세요.
풀이
Code
from collections import defaultdict
def solution(tickets):
global answer
# 1. DFS 함수 선언
def dfs(starting_point, route, count):
global answer
# 1-1. 종료 조건 설정
if count == 0:
# 출력 리스트에 route 삽입
answer.append(route)
# 1-2.
for destination in airport[starting_point]:
idx = airport[starting_point].index(destination)
# 현재 공항에서 도착지 제거
airport[starting_point].pop(idx)
# dfs 실행
dfs(destination, route + [destination], count - 1)
# 현재 공항에 도착지 삽입
airport[starting_point].insert(idx, destination)
answer = []
# 2. 모든 공항 정보 생성
airports = list(set(sum(tickets, [])))
# 3. 딕셔너리에 공항 정보를 key로, 빈 리스트를 value로 설정
airport = defaultdict()
for p in airports:
airport[p] = []
# 4.
for s, d in tickets:
# 딕셔너리의 출발지 인덱스에 도착지 삽입
airport[s].append(d)
# 5. DFS 실행
dfs('ICN', ['ICN'], len(tickets))
# 6. 결과 리턴
return sorted(answer)[0]
728x90
반응형
'Coding Test > Programmers' 카테고리의 다른 글
[Python/Programmers] 미로 탈출 (1) | 2023.08.31 |
---|---|
[Python/Programmers] 가장 큰 수 (0) | 2023.08.28 |
[Python/Programmers] 연속 펄스 부분 수열 (0) | 2023.08.27 |
[Python/Programmers] 거스름돈 (0) | 2023.08.27 |
[Python/Programmers] 최고의 집합 (0) | 2023.08.27 |