图的示意图

image.png
源码

  1. class node {
  2. constructor(value) {
  3. this.value = value;
  4. this.neighbour = [];
  5. }
  6. }
  7. const a = new node('a');
  8. const b = new node('b');
  9. const c = new node('c');
  10. const d = new node('d');
  11. const e = new node('e');
  12. a.neighbour.push(b);
  13. a.neighbour.push(c);
  14. b.neighbour.push(a);
  15. b.neighbour.push(c);
  16. b.neighbour.push(d);
  17. c.neighbour.push(a);
  18. c.neighbour.push(b);
  19. c.neighbour.push(d);
  20. d.neighbour.push(b);
  21. d.neighbour.push(c);
  22. d.neighbour.push(e);
  23. e.neighbour.push(d);
  24. /**
  25. * 图的深度优先搜索
  26. * @param {*} root
  27. * @param {*} target
  28. * @param {*} path
  29. * @returns
  30. */
  31. function deepSearch(root, target, path = []) {
  32. if (root == null) return false;
  33. if (path.includes(root) ) return false;
  34. console.log(root.value, target, 'value')
  35. if (root.value == target) return true;
  36. path.push(root);
  37. let result = false;
  38. for (let i = 0; i < root.neighbour.length; i++) {
  39. result = deepSearch(root.neighbour[i], target, path);
  40. if(result) return true;
  41. }
  42. return result;
  43. }
  44. console.log(deepSearch(a, 'e', []))