Skip to content

Instantly share code, notes, and snippets.

@rmdashrfv
Created August 14, 2020 20:44
Show Gist options
  • Select an option

  • Save rmdashrfv/946657b9cef8d06fe8f272241131baef to your computer and use it in GitHub Desktop.

Select an option

Save rmdashrfv/946657b9cef8d06fe8f272241131baef to your computer and use it in GitHub Desktop.
let graph = {
a: ['b', 'c', 'd'],
b: ['a', 'd'],
c: ['a', 'e'],
d: [],
e: ['d']
}
let pathExists = (start, end) => {
let remainingNodes = [start]
while (remainingNodes.length > 0) {
let currentNode = remainingNodes.shift() // take note of the current position in the graph
let availableMoves = graph[currentNode] // stored available vertices from current position
for (let move of availableMoves) { // iterate over every available move
remainingNodes.push(move) // store this move for later if we don't reach our goal
if (move === end) return true
}
}
return false
}
console.log(pathExists('b', 'e'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment