图的示意图
源码
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 {*} root
* @param {*} target
* @param {*} path
* @returns
*/
function deepSearch(root, target, path = []) {
if (root == null) return false;
if (path.includes(root) ) return false;
console.log(root.value, target, 'value')
if (root.value == target) return true;
path.push(root);
let result = false;
for (let i = 0; i < root.neighbour.length; i++) {
result = deepSearch(root.neighbour[i], target, path);
if(result) return true;
}
return result;
}
console.log(deepSearch(a, 'e', []))