无向图的深度和广度优先遍历
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);
}
}
}
}