Skip to content

Instantly share code, notes, and snippets.

@ObsidianCat
Last active March 15, 2024 15:12
Show Gist options
  • Save ObsidianCat/ea8a00bba285a9db150da173fa432f17 to your computer and use it in GitHub Desktop.
Save ObsidianCat/ea8a00bba285a9db150da173fa432f17 to your computer and use it in GitHub Desktop.
function buildItenary(options, startCity) {
const citiesMap = new Map()
options.forEach(([origin, dest]) => {
if (citiesMap.has(origin)) {
const stored = citiesMap.get(origin)
stored.push(dest)
citiesMap.set(origin, stored)
} else {
citiesMap.set(origin, [dest])
}
})
const originNode = new treeNode(startCity)
const queue = [originNode]
while (queue.length > 0) {
const curEl = queue.pop()
if (citiesMap.has(curEl.val)) {
citiesMap.get(curEl.val).forEach((val) => {
if (val === originNode.val) {
return
}
const node = new treeNode(val)
queue.push(node)
curEl.children.push(node)
})
}
}
// do dfs to collect all routes
const routes = []
dfs(originNode, routes, [])
// expect to get back
// [["Amsterdam", "London", "Minal"], ["Amsterdam", "Berlin"]
return routes
}
function dfs(node, routes, route) {
route.push(node.val)
if (node.children.length === 0) {
routes.push([...route])
return
}
node.children.forEach((node) => {
dfs(node, routes, [...route])
})
}
class treeNode {
constructor(val) {
this.val = val
this.children = []
}
}
const cities = [
["Amsterdam", "London"],
["Berlin", "Amsterdam"],
["Barcelona", "Berlin"],
["London", "Milan"],
["Amsterdam", "Berlin"],
]
console.log(buildItenary(cities, "Amsterdam"))
console.log(buildItenary(cities, "London"))
console.log(buildItenary(cities, "Milan"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment