[Programmers] 깊이/너비 우선 탐색(DFS/BFS) - 여행경로

zzenee·2022년 10월 12일
0

Algorithm&Coding-test

목록 보기
30/30
post-thumbnail

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

Problem

Code

import java.util.*;

class Solution {
    static int[] used;
    static List<String> routeList = new ArrayList<>();
    
    public void DFS(String targetSpot, int L, String route, String[][] tickets) {
        if (L == tickets.length) {
            routeList.add(route);
            return;
        } else {
            for (int i=0; i<tickets.length; i++) {
                if (used[i] == 0 && tickets[i][0].equals(targetSpot)) {
                    used[i] = 1;
                    DFS(tickets[i][1], L+1, route + " " + tickets[i][1], tickets);
                    used[i] = 0;
                }
            }
        }
    }
    
    public String[] solution(String[][] tickets) {
        used = new int[tickets.length];
        DFS("ICN", 0, "ICN", tickets);
        Collections.sort(routeList);
        return routeList.get(0).split(" ");
    }
}

Result

profile
꾸준히

0개의 댓글