dfs.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. var _ = require('../lodash')
  2. module.exports = dfs
  3. /*
  4. * A helper that preforms a pre- or post-order traversal on the input graph
  5. * and returns the nodes in the order they were visited. If the graph is
  6. * undirected then this algorithm will navigate using neighbors. If the graph
  7. * is directed then this algorithm will navigate using successors.
  8. *
  9. * Order must be one of "pre" or "post".
  10. */
  11. function dfs (g, vs, order) {
  12. if (!_.isArray(vs)) {
  13. vs = [vs]
  14. }
  15. var navigation = (g.isDirected() ? g.successors : g.neighbors).bind(g)
  16. const acc = []
  17. const visited = {}
  18. _.each(vs, function (v) {
  19. if (!g.hasNode(v)) {
  20. throw new Error('Graph does not have node: ' + v)
  21. }
  22. doDfs(g, v, order === 'post', visited, navigation, acc)
  23. })
  24. return acc
  25. }
  26. function doDfs (g, v, postorder, visited, navigation, acc) {
  27. if (!_.has(visited, v)) {
  28. visited[v] = true
  29. if (!postorder) { acc.push(v) }
  30. _.each(navigation(v), function (w) {
  31. doDfs(g, w, postorder, visited, navigation, acc)
  32. })
  33. if (postorder) { acc.push(v) }
  34. }
  35. }