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 {*} node
    27. * @param {*} target
    28. * @param {*} path
    29. * @returns
    30. */
    31. function bfc(node, target, path = []) {
    32. if (node == null || node.length == 0) return false;
    33. let nextNode = [];
    34. for (let i = 0; i < node.length; i++) {
    35. if (path.indexOf(node[i]) > -1 ) continue;
    36. console.log(node[i].value, target)
    37. path.push(node[i]);
    38. if (node[i].value == target) return true;
    39. else nextNode = nextNode.concat(node[i].neighbour)
    40. }
    41. return bfc(nextNode, target, path)
    42. }
    43. console.log(bfc([a], 'e'))