Created
March 4, 2018 17:53
-
-
Save kottenator/1ff1bbeb0b1746373d5382ab233bee02 to your computer and use it in GitHub Desktop.
Breadth-first graph traversal (BFS)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function breadthFirstTraverse(connections, start = 0) { | |
let stack = [[start, 0]]; // keep node index & current depth | |
let visited = new Set; | |
while (stack.length) { | |
let newStack = []; | |
log('Current stack:', stack); | |
for (let [i, depth] of stack) { | |
log(`Visit ${i} (depth: ${depth})`); | |
visited.add(i); | |
for (let k = 0; k < connections[i].length; k++) { | |
if (k === i) | |
continue; | |
if (connections[i][k] === 0) | |
continue; | |
if (visited.has(k)) { | |
log(`Not going from ${i} to ${k} (already visited):`, visited); | |
} else { | |
log(`Going from ${i} to ${k}.`); | |
newStack.push([k, depth + 1]); | |
} | |
} | |
log(`Finished with ${i}`); | |
} | |
stack = newStack; | |
} | |
} | |
function log(...args) { | |
if (log.enabled) { | |
console.log(...args); | |
} | |
} | |
log.enabled = true; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment