Skip to content

Instantly share code, notes, and snippets.

@lambdaydoty
Last active February 28, 2020 04:54
Show Gist options
  • Save lambdaydoty/06468d690bf87c009fd0a57ada8a5831 to your computer and use it in GitHub Desktop.
Save lambdaydoty/06468d690bf87c009fd0a57ada8a5831 to your computer and use it in GitHub Desktop.
(Recursive) Depth First Search & Breadth First Search
function dfs (x) {
x.visited = true
adjacent(x)
.forEach(y => y.visited || dfs(y))
}
// :: List Node -> List Node
function bfs0 (xs) {
xs.forEach(x => { x.visited = true })
return (!xs.length)
? xs
: xs.concat(
bfs0(xs.flatMap(
x =>
adjacent(x)
.filter(y => !y.visited)
))
)
}
function bfs (graph) {
return bfs0([pickSource(graph)])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment