无向图的深度和广度优先遍历(javascript)

无向图的深度和广度优先遍历

function Graph(v){    //Graph类的定义
    this.vertices=v;
    this.edges=0;     //边的条数
    this.adj=[];      //是一个二维数组,行是顶点信息,列是该顶点响铃顶点信息
    for(var i=0;i<this.vertices;i++){
        this.adj[i] =[];
        this.adj[i].push("");
    }
    this.addEdge = addEdge;    //添加边
    this.showGraph = showGroph;   //打印所有顶点和相邻顶点的列表
    this.DepthFirstTravel = DepthFirstTravel;  //深度遍历
    this.BreadthFirstTravel = BreadthFirstTravel;//广度遍历
    this.marked=[];   //存储所有已经访问过的节点
    for(var i=0;i<this.vertices;++i){
        this.marked[i]=false;    //false表示未访问
    }
}


function addEdge(v,w){
    this.adj[v].push(w);
    this.adj[w].push(v);
    this.edges++;
}



function showGraph(){
    for(var i=0;i<this.vertices;++i){
        console.log(i+" -> ");
        for(var j=0;j<this.vertices[i].length;++j){
            console.log(this.adj[i][j]+ " ");
        }
        console.log("<br/>");
    }
}



function DepthFirstTravel(v){  //深度遍历
    this.maked[v]=true;
    console.log(v);
    for(var w of this.adj[v]){
        if(!this.marked[w]){
            this.DepthFirstTravel(w);
        }
    }
}


function BreadthFirstTravel(v){  //广度遍历
    var queue=[];
    this.marked[v]=true;
    queue.push(v);
    while(queue.length>0){
        var v=queue.shift();
        console.log(v);
        for(var w of this.adj[v]){
            if(!this.marked[w]){
                this.marked[w]=true
                queue.push(w);
            }
        }
    }

}
    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/qq1024884152/article/details/76204362
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞