dfs.test.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import {
  2. findDFS,
  3. } from "../lib/util/dfs";
  4. import {
  5. assert,
  6. } from "../lib/util/assert";
  7. import * as _ from "lodash";
  8. const graph = new Map([
  9. [0, new Map([['a', 1], ['b', 2]])], // meaning: node 0 has two outgoing links: --'a'--> node 1 and --'b'--> node 2
  10. [1, new Map([['c', 0]])],
  11. [2, new Map([['d', 3]])],
  12. ]);
  13. function getNeighbors(node) {
  14. const outgoing = graph.get(node);
  15. if (outgoing === undefined) {
  16. return [];
  17. }
  18. return [...outgoing.entries()]
  19. }
  20. describe("DFS", () => {
  21. it("Find node one hop", () => {
  22. const path = findDFS(0, 1, getNeighbors);
  23. assert(_.isEqual(path, ['a']), "Expected node to be found.");
  24. })
  25. it("Find node two hops", () => {
  26. const path = findDFS(0, 3, getNeighbors);
  27. // There is more than one path from 0 to 3 (in fact, there are infinitely many, if we allow loops),
  28. // but we don't allow visiting the same element more than once, so only one path is possible:
  29. assert(_.isEqual(path, ['b', 'd']), "Expected node to be found.");
  30. });
  31. it("Find node zero hops", () => {
  32. const path = findDFS(0, 0, getNeighbors);
  33. assert(_.isEqual(path, []), "Expected node to be found.");
  34. })
  35. it("Find unreachable node", () => {
  36. const path = findDFS(3, 0, getNeighbors);
  37. assert(path === undefined, "Expected node to be unreachable.");
  38. });
  39. });