js实现基于邻接表的广度优先与深度优先搜索

function Graph() {
	//存放所有顶点的数组
    this.vertexes = [];
    //边对象,键为某个顶点,值为顶点所连接的其他顶点所构成的数组
    this.edges = {};
    //深度优先用来保存所访问过的顶点,存放在arr数组中
    this.map = new Map();
    this.arr = [];
}
//添加顶点到构造函数中,同时把edges对象的值都初始化为数组
Graph.prototype.addVertexes = function (v) {
    this.vertexes = v;
    for (let i = 0; i < v.length; i++) {
        this.edges[v[i]] = [];
    }
};
//添加边的信息
Graph.prototype.addEdges = function(start,end){
    this.edges[start].push(end);
    this.edges[end].push(start);
};
//广度优先搜索,类似于树的层序遍历,遍历图的一个连通分量
Graph.prototype.bfs = function(vertex) {
    if(this.vertexes.indexOf(vertex) == -1){
        return;
    }
    //传进来一个顶点vertex,存到arr中,入队列shift,添加到map集合中
    let arr = [];
    let shift = [];
    let map = new Map();
    arr.push(vertex);
    shift.push(vertex);
    map.set(vertex,true);
  //当队列不为空的时候一直循环,顶点出队列,并让顶点所连的所有另外的顶点入队列,直到把所有的顶点访问完
    while(shift.length != 0) {
        let aa = shift.shift();
        for(let i =0; i<this.edges[aa].length; i++){
        	//如果顶点没有访问过才访问保存并入队列,并且访问过之后加到map里面保存
            if(!map.has(this.edges[aa][i])){
                arr.push(this.edges[aa][i]);
                shift.push(this.edges[aa][i]);
                map.set(this.edges[aa][i],true);
            }
        }
    }
    return arr;
}
//深度优先搜索,类似于树的先序遍历
Graph.prototype.dfs = function(vertex) {
    if(this.vertexes.indexOf(vertex) == -1){
        return;
    }
    this.arr.push(vertex);
    this.map.set(vertex,true);
    for(let i=0; i<this.edges[vertex].length; i++){
        if(!this.map.has(this.edges[vertex][i])){
        	//递归实现深度优先搜索
            this.dfs(this.edges[vertex][i]);
        }
    }
    return this.arr;
}

let p1 = new Graph();
let aa =['A','B','C','D','E','F'];
p1.addVertexes(aa);
p1.addEdges('A','D');
p1.addEdges('A','C');
p1.addEdges('C','B');
p1.addEdges('A','E');
p1.addEdges('B','E');
p1.addEdges('A','F');
console.log(p1.vertexes);
console.log(p1.edges);
console.log(p1.bfs('A'));
console.log(p1.dfs('A'));


运行结果:
[Running] node "c:\Users\Administrator\Desktop\uu.js"
[ 'A', 'B', 'C', 'D', 'E', 'F' ]
{
  A: [ 'D', 'C', 'E', 'F' ],
  B: [ 'C', 'E' ],
  C: [ 'A', 'B' ],
  D: [ 'A' ],
  E: [ 'A', 'B' ],
  F: [ 'A' ]
}
[ 'A', 'D', 'C', 'E', 'F', 'B' ]
[ 'A', 'D', 'C', 'B', 'E', 'F' ]

[Done] exited with code=0 in 0.134 seconds
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大钰螺旋丸

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值