프로그래머스 DFS/BFS 여행경로

jaegeunsong97·2023년 2월 28일
0
post-thumbnail

import java.util.*;

class Solution {
	static ArrayList<String> list = new ArrayList<>();
    static boolean useTickets[];
	
	public String[] solution(String[][] tickets) {
    	// [["ICN", "JFK"], ["HND", "IAD"], ["JFK", "HND"]]
    	userTickets = new boolean[tickets.length]; // 3
        
        dfs(0, "ICN", "ICN", tickets);
        Collection.sort(list);
        
        return list.get(0).split(" ");
    }
    
    // 깊이, 현재위치, 방문한 여행경로, tickets 배열
    static void dfs(int depth, String now, String path, String[][] tickets) {
    	// 현재위치랑 다음 가야할 곳의 출발지를 비교하여 
        // depth가 티켓의 수와 같으면 해당 경로를 리스트에 담는다.
        // 탐색이 끝나면 list에는 모든 경로가 담겨져 있다.
    	if (depth == tickets.length) { // 3
        	list.add(path);
            return;
        }
        
        // [["ICN", "JFK"], ["HND", "IAD"], ["JFK", "HND"]]
        for (int i = 0; i < useTickets.length; i++) { // 3번 순회
        	// 현재 위치랑 tickets[i][0]가 일치하고 
        	if (!useTickets[i] && now.equals(tickets[i][0]) {
            	useTickets[i] = true;
                dfs(depth + 1, tickets[i][1], path + " " + tickets[i][1], tickets);
                userTickets[i] = false;
            }
        }
    }
}
profile
현재 블로그 : https://jasonsong97.tistory.com/

0개의 댓글