Coding Test/Programmers

[Python/Programmers] 여행 경로

NLP Developer 2023. 8. 28. 00:41
728x90
반응형

https://school.programmers.co.kr/learn/courses/30/lessons/43164

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

문제 설명

주어진 항공권을 모두 이용하여 여행경로를 짜려고 합니다. 항상 "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
반응형