[파이썬/프로그래머스]여행경로
링크: https://programmers.co.kr/learn/courses/30/lessons/43164
코딩테스트 연습 - 여행경로
[["ICN", "SFO"], ["ICN", "ATL"], ["SFO", "ATL"], ["ATL", "ICN"], ["ATL","SFO"]] ["ICN", "ATL", "ICN", "SFO", "ATL", "SFO"]
programmers.co.kr
문제:
주어진 항공권을 모두 이용하여 여행경로를 짜려고 합니다. 항상 "ICN" 공항에서 출발합니다.
항공권 정보가 담긴 2차원 배열 tickets가 매개변수로 주어질 때, 방문하는 공항 경로를 배열에 담아 return 하도록 solution 함수를 작성해주세요.
만일 가능한 경로가 2개 이상일 경우 알파벳 순서가 앞서는 경로를 return 합니다.
코드:
# DFS
from collections import defaultdict
def solution(tickets):
answer = []
graph = defaultdict(list)
for dept, arrv in sorted(tickets):
graph[dept].append(arrv)
def dfs(dept):
while graph[dept]:
dfs(graph[dept].pop(0))
answer.append(dept)
dfs('ICN')
return answer[::-1]
리트코드의 'Reconstruct Itinerary'문제와 거의 같다. 알파벳 순서가 앞서는 경로를 return하라는 부분을 빼면 거의 같다고 할 수준의 문제다.
https://leetcode.com/problems/reconstruct-itinerary/
Reconstruct Itinerary - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
2달 쯤 전에 풀었던 문제인데, 위에 보면 출발지만 다르고 코드는 똑같다.
이거랑 비슷한 문제를 풀고 싶으면, Leetcode에서 추천해주는 DFS, Graph문제를 풀면 될거같다.
https://leetcode.com/tag/depth-first-search/
Depth-first Search - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
https://leetcode.com/tag/graph/
Graph - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com