๋ฐ์ํ
https://programmers.co.kr/learn/courses/30/lessons/43164?language=java
๋ฌธ์ ์ค๋ช
์ฃผ์ด์ง ํญ๊ณต๊ถ์ ๋ชจ๋ ์ด์ฉํ์ฌ ์ฌํ๊ฒฝ๋ก๋ฅผ ์ง๋ ค๊ณ ํฉ๋๋ค. ํญ์ "ICN" ๊ณตํญ์์ ์ถ๋ฐํฉ๋๋ค.
ํญ๊ณต๊ถ ์ ๋ณด๊ฐ ๋ด๊ธด 2์ฐจ์ ๋ฐฐ์ด tickets๊ฐ ๋งค๊ฐ๋ณ์๋ก ์ฃผ์ด์ง ๋, ๋ฐฉ๋ฌธํ๋ ๊ณตํญ ๊ฒฝ๋ก๋ฅผ ๋ฐฐ์ด์ ๋ด์ return ํ๋๋ก solution ํจ์๋ฅผ ์์ฑํด์ฃผ์ธ์.
์ ํ ์ฌํญ
- ๋ชจ๋ ๊ณตํญ์ ์ํ๋ฒณ ๋๋ฌธ์ 3๊ธ์๋ก ์ด๋ฃจ์ด์ง๋๋ค.
- ์ฃผ์ด์ง ๊ณตํญ ์๋ 3๊ฐ ์ด์ 10,000๊ฐ ์ดํ์ ๋๋ค.
- tickets์ ๊ฐ ํ [a, b]๋ a ๊ณตํญ์์ b ๊ณตํญ์ผ๋ก ๊ฐ๋ ํญ๊ณต๊ถ์ด ์๋ค๋ ์๋ฏธ์ ๋๋ค.
- ์ฃผ์ด์ง ํญ๊ณต๊ถ์ ๋ชจ๋ ์ฌ์ฉํด์ผ ํฉ๋๋ค.
- ๋ง์ผ ๊ฐ๋ฅํ ๊ฒฝ๋ก๊ฐ 2๊ฐ ์ด์์ผ ๊ฒฝ์ฐ ์ํ๋ฒณ ์์๊ฐ ์์๋ ๊ฒฝ๋ก๋ฅผ return ํฉ๋๋ค.
- ๋ชจ๋ ๋์๋ฅผ ๋ฐฉ๋ฌธํ ์ ์๋ ๊ฒฝ์ฐ๋ ์ฃผ์ด์ง์ง ์์ต๋๋ค.
ํ์ด
DFS ๋ก ํด๊ฒฐ! ์ญ์ ๋ฏฟ๊ณ ์ฐ๋ DFS ๐
์ฒ์์ tickets์ ์ค๋ฆ์ฐจ์์ผ๋ก ๋ฏธ๋ฆฌ ์ ๋ ฌํด์ค๋ค! ๐ ์ฌ๋ฌ๊ฐ์ง ๊ฒฝ๋ก๊ฐ ์๋ค๋ฉด ์ํ๋ฒณ ์์๋ก ์์ ๊ฒฝ๋ก๊ฐ ์ถ๋ ฅ๋์ด์ผํด์โผ๏ธ
๊ทธ๋ฆฌ๊ณ DFS๋ฅผ ๋๋ฆฌ๋ฉด ๋์๐คทโ๏ธ
์ฝ๋
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class ์ฌํ๊ฒฝ๋ก {
static boolean[] isVisited;
static List<String> ansList;
public static String[] solution(String[][] tickets) {
String[] answer = {};
isVisited = new boolean[tickets.length];
ansList = new ArrayList<>();
Arrays.sort(tickets, new Comparator<String[]>(){
@Override
public int compare(String[] o1, String[] o2) {
if(o1[0].toString().equals(o2[0].toString()))
return o1[1].toString().compareTo(o2[1].toString());
return o1[0].toString().compareTo(o2[0].toString());
}
});
DFS("ICN", tickets, 0, "ICN");
answer = ansList.get(0).split(" ");
return answer;
}
private static void DFS(String now, String[][] tickets, int cnt, String result) {
if(cnt == tickets.length){
ansList.add(result);
return;
}
for(int i = 0 ; i < tickets.length ; i++){
if(tickets[i][0].equals(now) && !isVisited[i]){
isVisited[i] = true;
DFS(tickets[i][1], tickets, cnt+1, result+" "+tickets[i][1]);
isVisited[i] = false;
}
}
}
public static void main(String[] args) {
String[][] tickets = {{"ICN", "SFO"}, {"ICN", "ATL"}, {"SFO", "ATL"}, {"ATL", "ICN"}, {"ATL","SFO"}};
String[] ans = solution(tickets);
for(String a : ans){
System.out.println(a);
}
}
}
728x90
๋ฐ์ํ