dfs.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536
  1. // Generic depth-first search.
  2. // getNeighbors should return an array of 'outgoing links', where each link is a pair [label, neighboring_element]
  3. // 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.
  4. // 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'.
  5. // If not reachable, returns undefined.
  6. export function findDFS<T,L>(start: T, searchFor: T, getNeighbors: (T)=>Array<[L,T]>): L[] | undefined {
  7. const alreadyVisited = new Set<T>([start]); // only visit every 'thing' once
  8. let recursiveInvocations = 0;
  9. function findDFSRecursive(current: T, currentPath: L[]): L[] | undefined {
  10. recursiveInvocations++;
  11. if (current === searchFor) {
  12. return currentPath;
  13. }
  14. const neighbors = getNeighbors(current);
  15. // console.log("current", current, "neighbors:", neighbors)
  16. for (const [link, neighbor] of neighbors) {
  17. if (alreadyVisited.has(neighbor)) {
  18. continue;
  19. }
  20. alreadyVisited.add(neighbor);
  21. const recursiveResult = findDFSRecursive(neighbor, [...currentPath, link]);
  22. if (recursiveResult !== undefined) {
  23. return recursiveResult;
  24. }
  25. // continue with next neighbor...
  26. }
  27. }
  28. const result = findDFSRecursive(start, []);
  29. // console.log("findDFS recursiveInvocations (performance metric, less is better):", recursiveInvocations);
  30. return result;
  31. }