dfs.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.findDFS = void 0;
  4. // Generic depth-first search.
  5. // getNeighbors should return an array of 'outgoing links', where each link is a pair [label, neighboring_element]
  6. // neighbors are visited in the order that getNeighbors returns them, so getNeighbors can be optimized (e.g., via some heuristic) to minimize the number of visits.
  7. // If the element 'searchFor' was reachable from the 'start', returns a PATH, i.e., an array of link-labels to get from start to 'searchFor'.
  8. // If not reachable, returns undefined.
  9. function findDFS(start, searchFor, getNeighbors) {
  10. const alreadyVisited = new Set([start]); // only visit every 'thing' once
  11. let recursiveInvocations = 0;
  12. function findDFSRecursive(current, currentPath) {
  13. recursiveInvocations++;
  14. if (current === searchFor) {
  15. return currentPath;
  16. }
  17. const neighbors = getNeighbors(current);
  18. // console.log("current", current, "neighbors:", neighbors)
  19. for (const [link, neighbor] of neighbors) {
  20. if (alreadyVisited.has(neighbor)) {
  21. continue;
  22. }
  23. alreadyVisited.add(neighbor);
  24. const recursiveResult = findDFSRecursive(neighbor, [...currentPath, link]);
  25. if (recursiveResult !== undefined) {
  26. return recursiveResult;
  27. }
  28. // continue with next neighbor...
  29. }
  30. }
  31. const result = findDFSRecursive(start, []);
  32. // console.log("findDFS recursiveInvocations (performance metric, less is better):", recursiveInvocations);
  33. return result;
  34. }
  35. exports.findDFS = findDFS;
  36. //# sourceMappingURL=dfs.js.map