1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
| function Graph() { this.vertexes = [] this.edges = new Dictionay()
Graph.prototype.addVertex = function (v) { this.vertexes.push(v) this.edges.set(v, []) } Graph.prototype.addEdge = function (v1, v2) { this.edges.get(v1).push(v2) this.edges.get(v2).push(v1) } Graph.prototype.toString =function(){ let resultString="" for(let i =0;i<this.vertexes.length;i++ ){ resultString += this.vertexes[i]+ "->" let vEdges=this.edges.get(this.vertexes[i]) for(let j=0;j<vEdges.length;j++){ resultString += vEdges[j] + " " } resultString +='\n' } return resultString } Graph.prototype.initializeColor=function(){ var colors= [] for(var i=0;i<this.vertexes.length;i++){ colors[this.vertexes[i]]="white" } return colors } Graph.prototype.bfs=function(initv,handler){ let colors= this.initializeColor() let queue = new Queue() queue.enqueue(initv) while(!queue.isEmpty()){ let v=queue.dequeue() let vList=this.edges.get(v)
colors[v]='gray' for(let i=0;i<vList.length;i++){ let e = vList[i] if(colors[e]=='white'){ colors[e]='gray' queue.enqueue(e) } } handler(v)
colors[v]='black' } } Graph.prototype.dfs=function(init,handler){ var colors=this.initializeColor() this.dfsVisit(init,colors,handler) } Graph.prototype.dfsVisit=function(v,colors,handler){ colors[v]='gray' handler(v) var vList=this.edges.get(v) for(var i =0; i<vList.length;i++){ var e = vList[i] if(colors[e]=='white'){ this.dfsVisit(e,colors,handler) } } colors[v]='black'
} }
|