美文网首页
图的深度优先搜索

图的深度优先搜索

作者: bestCindy | 来源:发表于2020-07-19 00:26 被阅读0次
    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.push(b);
    a.neighbor.push(c);
    b.neighbor.push(a);
    b.neighbor.push(c);
    b.neighbor.push(d);
    c.neighbor.push(a);
    c.neighbor.push(b);
    c.neighbor.push(d);
    d.neighbor.push(b);
    d.neighbor.push(c);
    d.neighbor.push(e);
    e.neighbor.push(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);//把当前节点放到已经查看过的路径里面
    
        let result = false;
        for (let i = 0; i < node.neighbor.length; i++) {
            result |= deepSearch(node.neighbor[i], target, path);
        }
        return !!result;
    }
    
    console.log(deepSearch(b, "n", []))
    

    相关文章

      网友评论

          本文标题:图的深度优先搜索

          本文链接:https://www.haomeiwen.com/subject/jycqkktx.html