Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

22.01.20 - [PG] 여행경로 #199

Closed
suhyunsim opened this issue Jan 21, 2022 · 0 comments
Closed

22.01.20 - [PG] 여행경로 #199

suhyunsim opened this issue Jan 21, 2022 · 0 comments
Assignees
Labels
DFS 깊이 우선 탐색 lv.3 프로그래머스 - level 3 성공 맞은 문제

Comments

@suhyunsim
Copy link
Owner

문제

핵심 아이디어

  • DFS로 풀이
  • dfs 전에 tickets 정렬하면 첫번째 가능한 경로만 구하면 됨

어려운 점, 실수

풀이

package main.java.com.poogle.PG.Q43164;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {

    static boolean[] visited;
    static List<String> result;
    static final String START = "ICN";

    public static void main(String[] args) {
        System.out.println(Arrays.toString(solution(new String[][]{{"ICN", "JFK"}, {"HND", "IAD"}, {"JFK", "HND"}})));
        System.out.println(Arrays.toString(solution(new String[][]{{"ICN", "SFO"}, {"ICN", "ATL"}, {"SFO", "ATL"}, {"ATL", "ICN"}, {"ATL", "SFO"}})));
    }

    public static String[] solution(String[][] tickets) {
        int cnt = 0;
        visited = new boolean[tickets.length];
        result = new ArrayList<>();
        Arrays.sort(tickets, ((o1, o2) -> {
            if (o1[0].equals(o2[0])) {
                return o1[1].compareTo(o2[1]);
            }
            return o1[0].compareTo(o2[0]);
        }));
        dfs(cnt, START, START, tickets);
        return result.get(0).split(" ");
    }

    private static void dfs(int cnt, String now, String route, String[][] tickets) {
        if (cnt == tickets.length) {
            result.add(route);
            return;
        }
        for (int i = 0; i < tickets.length; i++) {
            if (!visited[i] && tickets[i][0].equals(now)) {
                visited[i] = true;
                dfs(cnt + 1, tickets[i][1], route + " " + tickets[i][1], tickets);
                visited[i] = false;
            }
        }
    }
}
@suhyunsim suhyunsim added 성공 맞은 문제 lv.3 프로그래머스 - level 3 DFS 깊이 우선 탐색 labels Jan 21, 2022
@suhyunsim suhyunsim self-assigned this Jan 21, 2022
@suhyunsim suhyunsim changed the title 22.01.21 - [PG] 여행경로 22.01.20 - [PG] 여행경로 Jan 21, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
DFS 깊이 우선 탐색 lv.3 프로그래머스 - level 3 성공 맞은 문제
Projects
None yet
Development

No branches or pull requests

1 participant