https://school.programmers.co.kr/learn/courses/30/lessons/43164#
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
처음 작성한 코드는 테스트케이스 1번 2번에서 실패했다.
그 이유는 위 케이스에서 ICN에서 출발하여 알파벳순으로 더 먼저오는 AAA로 가는 경로만 구했기 때문에 모든 경로를 탐사하는 루트를 구하지 못했다.
따라서 모든 경로를 구하기 위해서 백트래킹을 해야된다는 것을 알게 되었다.
<정답코드>
import java.util.*;
class Solution {
public static boolean[] visit;
public static List<String> result = new LinkedList<>();
public String[] solution(String[][] tickets) {
String[] answer =new String[tickets.length+1];
visit = new boolean[tickets.length];
Arrays.sort(tickets, Comparator.comparing(o -> o[1])); //도착지 알파벳순으로 정렬
dfs(tickets,"ICN",0,new ArrayList<>());
return result.toArray(new String[0]);
}
public void dfs(String[][] tickets,String current,int count,List<String> path){
path.add(current);
if(count==tickets.length){
if(result.isEmpty() || path.toString().compareTo(result.toString())<0){
result.clear();
result.addAll(path);
}
return;
}
for(int i=0; i<tickets.length; i++){
if(tickets[i][0].equals(current) && visit[i]==false){
visit[i]=true;
dfs(tickets,tickets[i][1],count+1,new ArrayList<>(path));
visit[i]=false; //다시 방문 전 상태로 만들어 모든 경로 탐색 가능
}
}
return;
}
}
'알고리즘 > DFS,BFS' 카테고리의 다른 글
프로그래머스 - 전력망을 둘로 나누기[Java][BFS] (0) | 2025.02.22 |
---|---|
프로그래머스 - 무인도 여행[Java] (0) | 2025.02.15 |
프로그래머스 - 네트워크[Java] (2) | 2025.02.08 |
프로그래머스 - 게임 맵 최단거리(Java) (0) | 2025.01.23 |
프로그래머스 - 타겟 넘버(Java) (0) | 2025.01.23 |