Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 65b8987

Browse files
authored
Merge pull request #359 from Samuel-Hinchliffe/main
Create 332-Reconstruct-Itinerary.js
2 parents e5fe18b + 3ea4354 commit 65b8987

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* @param {string[][]} tickets
3+
* @return {string[]}
4+
*/
5+
var findItinerary = function (tickets) {
6+
const flight_paths = new Map();
7+
const flight_path_order = ["JFK"];
8+
9+
tickets = tickets.sort();
10+
11+
for (const [source, dest] of tickets) {
12+
let edges = [];
13+
if (flight_paths.has(source)) {
14+
edges = flight_paths.get(source);
15+
}
16+
edges.push(dest);
17+
flight_paths.set(source, edges);
18+
}
19+
20+
const depth_first_search = (city) => {
21+
if (flight_path_order.length === tickets.length + 1) return true;
22+
23+
const cities_to_go_to = flight_paths.get(city) || [];
24+
if (!cities_to_go_to.length) return false;
25+
26+
const cities_copied = Array.from(cities_to_go_to);
27+
28+
for (const other_city of cities_copied) {
29+
flight_path_order.push(other_city);
30+
cities_to_go_to.shift();
31+
32+
if (depth_first_search(other_city)) {
33+
return flight_path_order;
34+
} else {
35+
flight_path_order.pop();
36+
cities_to_go_to.push(other_city);
37+
}
38+
}
39+
40+
return false;
41+
};
42+
43+
return depth_first_search("JFK");
44+
};

0 commit comments

Comments
 (0)