Last active
February 28, 2020 04:54
-
-
Save lambdaydoty/06468d690bf87c009fd0a57ada8a5831 to your computer and use it in GitHub Desktop.
(Recursive) Depth First Search & Breadth First Search
This file contains hidden or 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 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