1
function dfs(edges, s = `JFK`, ans = [`JFK`]) {2
//run dfs, starting node being `JFK`3
if (!edges[s] || edges[s].length == 0) {4
//if currenctly reached node has its adjacent list empty5
let isAllTravelled = 1;6
Object.values(edges).forEach((ele) => {7
if (ele.length > 0) isAllTravelled = 0;8
}); // check if every edge has been travelled i.e all adjacentLists should be empty10
return false; //returns false when there are more edges to travel , but from current node we cannot move anywhere else11
else return ans; // return true if from current node we cannot move anywhere else and all the edges have been travelled as well14
let myAL = edges[s].sort(); // sort the Adjacency List of current node lexicographically15
for (let i = 0; i < myAL.length; i++) {16
// start by taking the lexicographically smallest node and run dfs17
ans.push(myAL[i]); // add current node into answer array19
...edges[s].slice(0, edges[s].indexOf(myAL[i])),20
...edges[s].slice(edges[s].indexOf(myAL[i]) + 1),21
]; // remove the currently edges travelled from adjacency List22
let xx = dfs(edges, myAL[i], ans); //here runs the dfs24
// if dfs result of current node could not travel all edges from current node25
ans.pop(); // pop out current accounted node from answer26
edges[s].push(myAL[i]); //put back the edge into adjacency list assmuing we should not visit this edge at this point as it doesnt leads to answer from here currenlt27
} else return xx; // if dfs result of current node could travel all edges from current node return the answer array30
var findItinerary = function (tickets) {31
let edges = {}; //our adjacency list32
tickets.forEach((ticket) => {33
if (!edges[ticket[0]]) {34
edges[ticket[0]] = [];36
edges[ticket[0]].push(ticket[1]);39
let ans = dfs(edges); // run dfs