-
Notifications
You must be signed in to change notification settings - Fork 0
/
여행경로.js
71 lines (55 loc) · 1.45 KB
/
여행경로.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Solution 1
function solution1(tickets) {
let finalRoute = [];
const route = [];
const ticketCount = tickets.length;
const visited = Array.from({ length: ticketCount }, () => false);
tickets.sort();
function dfs(airport, count) {
route.push(airport);
if (count === ticketCount) {
finalRoute = route;
return true;
}
for (let i = 0; i < ticketCount; i++) {
if (!visited[i] && tickets[i][0] === airport) {
visited[i] = true;
if (dfs(tickets[i][1], count + 1)) {
return true;
}
visited[i] = false;
}
}
route.pop();
return false;
}
dfs('ICN', 0);
return finalRoute;
}
// Solution 2
function solution2(tickets) {
const totalTicketCount = tickets.length;
const visited = Array.from({ length: totalTicketCount }, () => false);
const route = [];
const finalRoutes = [];
tickets.sort();
function dfs(airport, ticketCount) {
if (ticketCount === totalTicketCount) {
finalRoutes.push(route.slice());
} else {
for (let i = 0; i < totalTicketCount; i++) {
const [departureAirport, arrivalAirport] = tickets[i];
if (!visited[i] && departureAirport === airport) {
visited[i] = true;
route.push(arrivalAirport);
dfs(arrivalAirport, ticketCount + 1);
visited[i] = false;
route.pop();
}
}
}
}
route.push('ICN');
dfs('ICN', 0);
return finalRoutes[0];
}