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