
源码
class node {constructor(value) {this.value = value;this.neighbour = [];}}const a = new node('a');const b = new node('b');const c = new node('c');const d = new node('d');const e = new node('e');a.neighbour.push(b);a.neighbour.push(c);b.neighbour.push(a);b.neighbour.push(c);b.neighbour.push(d);c.neighbour.push(a);c.neighbour.push(b);c.neighbour.push(d);d.neighbour.push(b);d.neighbour.push(c);d.neighbour.push(e);e.neighbour.push(d);/*** 图的广度优先搜索* @param {*} node* @param {*} target* @param {*} path* @returns*/function bfc(node, target, path = []) {if (node == null || node.length == 0) return false;let nextNode = [];for (let i = 0; i < node.length; i++) {if (path.indexOf(node[i]) > -1 ) continue;console.log(node[i].value, target)path.push(node[i]);if (node[i].value == target) return true;else nextNode = nextNode.concat(node[i].neighbour)}return bfc(nextNode, target, path)}console.log(bfc([a], 'e'))
