JavaScript图结构
function Graph(){
this.vertexes = []
this.edges = {}
Graph.prototype.addVertex = function(v){
this.vertexes.push(v)
this.edges[v] = []
}
Graph.prototype.addEdge = function(v1, v2){
this.edges[v1].push(v2)
this.edges[v2].push(v1)
}
Graph.prototype.toString = function(){
let resultString = ''
this.vertexes.forEach(eachVertex => {
let eachStr = eachVertex + ' => '
this.edges[eachVertex].forEach(eachEdge => {
eachStr += eachEdge + ' '
})
resultString += eachStr + '\n'
})
return resultString
}
Graph.prototype.initColor = function(){
let colors = {}
this.vertexes.forEach(item => {
colors[item] = 'white'
})
return colors
}
Graph.prototype.bfs = function(firstV, callback){
let colors = this.initColor()
let queue = []
queue.push(firstV)
colors[firstV] = 'gray'
while(queue.length != 0){
let currentV = queue.shift()
let listV = this.edges[currentV]
listV.forEach(item => {
if (colors[item] == 'white'){
colors[item] = 'gray'
queue.push(item)
}
})
callback(currentV)
colors[currentV] = 'black'
}
}
Graph.prototype.dfs = function(firstV, callback){
let colors = this.initColor()
this.dfsTraversal(firstV, colors, callback)
}
Graph.prototype.dfsTraversal = function(v, colors, callback){
colors[v] = 'gray'
callback(v)
let listV = this.edges[v]
listV.forEach(item => {
if (colors[item] == 'white'){
this.dfsTraversal(item, colors, callback)
}
})
colors[v] = 'black'
}
}