본문 바로가기

프로그램 강좌

[프로그래머스]여행경로 - javascript

구글링 검색

검색 후 해석. 알고나면 참 아무것도 아닌데 아직은 어렵네요.

function solution(tickets) {
    let routes = [];

    function DFS(extra, current, route){
        // extra(잔여티켓): [["ICN", "JFK"], ["HND", "IAD"], ["JFK", "HND"]]
        // current(현재위치): "ICN"
        // route(여행경로): ["ICN"]
        if (extra.length === 0) {
            routes.push(route); //잔여티켓 연산이 끝나면 routes로 정보전송
        } //티켓 모두 사용
        else {
            extra.forEach(([s, e], index) => {
                //s: 출발, e: 목적지
                //index: 인덱스번호
                if (current === s) {
                    const newExtra = extra.slice();
                    newExtra.splice(index, 1); //사용했던 티켓은 빼버린다.

                    DFS(newExtra, e, route.concat(e));
                    //남은 잔여티켓, 새목적지를 입력해서 재호출
                }
            });
        }
    };
    DFS(tickets, 'ICN', ['ICN']);
    //초기값 설정
    return routes.sort()[0];
}
728x90