forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0332-reconstruct-itinerary.js
46 lines (33 loc) · 993 Bytes
/
0332-reconstruct-itinerary.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
/**
* https://leetcode.com/problems/reconstruct-itinerary/
* @param {string[][]} tickets
* @return {string[]}
*/
var findItinerary = (tickets) => {
tickets.sort();
const graph = buildGraph(tickets);
return dfs(tickets, graph);
};
const dfs = (tickets, graph, city = 'JFK', path = ['JFK']) => {
const isBaseCase = (path.length === (tickets.length + 1));
if (isBaseCase) return true;
const queue = (graph.get(city) || []);
const isEmpty = (queue.length === 0);
if (isEmpty) return false;
for (const nextCity of queue.slice()) {
path.push(nextCity);
queue.shift();
if (dfs(tickets, graph, nextCity, path)) return path;
path.pop();
queue.push(nextCity);
}
return false;
};
const buildGraph = (tickets, graph = new Map()) => {
for (const [ src, dst ] of tickets) {
const edges = (graph.get(src) || []);
edges.push(dst);
graph.set(src, edges);
}
return graph;
}