【算法】图的深度优先搜索和广度优先搜索

123 阅读1分钟

一、图的深度优先搜索

function Node(value) {
    this.value = value;
    this.neighbor  = [];
}
let a = new Node("a");
let b = new Node("b");
let c = new Node("c");
let d = new Node("d");
let e = new Node("e");

a.neighbor = [b, c];
b.neighbor = [a, c, d];
c.neighbor = [a, b, d];
d.neighbor = [b, c, e];
e.neighbor = [d]

function deepSearch(node, target, path) {
    if (node == null) return false;
    if (path.indexOf(node) > -1) return false; //树不会形成环,所以不用判断有没有走过
    if (node.value == target) return true;
    path.push(node); //path记录走过的节点,防止两个节点之间重复搜索
    let result = false;
    for (let i = 0; i < node.neighbor.length; i ++) {
        result |= deepSearch(node.neighbor[i], target, path);
    }
    return result ? true : false;
}
console.log(deepSearch(b, "e", []));

二、图的广度优先搜素

function bfs(nodes, target, path) {
    if (nodes == null || nodes.length == 0) return false;
    let nextNodes = [];
    for (let i = 0; i < nodes.length; i ++) {
        if (path.indexOf(nodes[i]) > -1) continue;
        path.push(nodes[i]);
        if (nodes[i].value == target) return true;
        else nextNodes = nextNodes.concat(nodes[i].neighbor);
    }
    return bfs(nextNodes, target, path)
}
console.log(bfs([d], "e", []))