web123456

javascript data structure 8-picture (Graph)

function Graph(v){ this.vertices=v; this.edges=0; this.adj=[]; for(var i=0;i<this.vertices;++i){ this.adj[i]=[]; // [i].push(""); } this.addEdge=addEdge; this.showGraph=showGraph; //Depth priority search this.dfs=dfs; this.marked=[]; for(var i=0;i<this.vertices;++i){ this.marked[i]=false; } // Breadth search this.bfs=bfs; } // Add vertex function addEdge(v,w){ this.adj[v].push(w); this.adj[w].push(v); this.edges++; } //Travel function showGraph(){ for(var i=0;i<this.vertices;++i){ ('<br/>'); (i+"-->"); for(var j=0;j<this.vertices;++j){ if(this.adj[i][j]!=undefined){ (this.adj[i][j]+' '); } } } } //Depth priority search function dfs(v){ //var w; this.marked[v]=true; if(this.adj[v]!=undefined){ ("<br/>Accessed Node:"+v); } // for(var w in [v]){ //([0].length); var w=this.adj[v].shift(); while(w!=undefined){ if(!this.marked[w]){ this.dfs(w); } w=this.adj[v].shift(); } //(w); //([v]); } // Breadth search function bfs(s){ var queue=[]; this.marked[s]=true; (s);//Add to the end of the team var w; //Storing adjacency table while(>0){ var v=();//Delete from the team leader if(v!=undefined){ ("<br/>Accessed Node:"+v); } w=this.adj[v].shift(); while(w!=undefined){ if(!this.marked[w]){ this.marked[w]=true; (w); } w=this.adj[v].shift(); } } } //test var graph=new Graph(5); (0,1); (0,2); (1,3); (2,4); //(graph); //(); (); ("<br/>"); ("======= Depth priority search======"); (0); ("<br/>"); ("======Breadth priority search======"); var graph1=new Graph(5); (0,1); (0,2); (1,3); (2,4); (0);