图(Graph)是由顶点和连接顶点的边构成的离散结构。在计算机科学中,图是最灵活的数据结构之一,很多问题都可以使用图模型进行建模求解。例如:人与人之间的社交与关系网络、找到两个城市之间的最短路径等等。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图结构</title>
</head>
<body>
<script>
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)
}
//toString方法
Graph.prototype.toSting=function(){
var resultString=''
for(var i=0;i<this.vertexes.length;i++){
resultString+=this.vertexes[i]+'->'
var vEdges=this.edges[this.vertexes[i]]
for(var k=0;k<vEdges.length;k++){
resultString+=vEdges[k]+" "
}
resultString+="\n"
}
return resultString
}
//初始化颜色,white 未被访问,grey 访问未被探索,black访问并探索
Graph.prototype.initializeColor=function(){
var colors=[]
for(var i=0;i<this.vertexes.length;i++){
colors[this.vertexes[i]]='white'
}
return colors
}
//广度优先搜索BFS
Graph.prototype.bfs=function(initV,handler){
//初始化颜色
var colors=this.initializeColor()
//将顶点放入数组中
var arr=[]
arr.push(initV)
while(arr.length!==0){
//取出顶点
var v=arr.shift()
//把v设置成灰色
colors[v]='grey'
//获取顶点相连顶点,并加入数组中
for(var i=0; i<this.edges[v].length;i++){
if(colors[this.edges[v][i]]=='white'){
colors[this.edges[v][i]]='grey'
arr.push(this.edges[v][i])
}
}
handler(v)
colors[v]='black'
}
}
//深度优先递归
function recursionDfs(v,colors,handler){
//颜色设置为灰色
colors[v]='grey'
//处理顶点
handler(v)
//访问相相连顶点
for(var i=0;i<this.edges[v].length;i++){
if(colors[this.edges[v][i]]=='white'){
recursionDfs.call(this,this.edges[v][i],colors,handler)
}
}
//设置成black
colors[v]='black'
}
//深度优先搜索DFS
Graph.prototype.dfs=function(initV,handler){
//初始化颜色
var colors=this.initializeColor()
recursionDfs.call(this,initV,colors,handler)
}
//测试代码
var gra=new Graph()
var vertexesExp=['A','B','C','D','E','F','G','H']
for(var vertex of vertexesExp){
gra.addVertex(vertex)
}
gra.addEdge('A','B')
gra.addEdge('A','C')
gra.addEdge('A','D')
gra.addEdge('C','D')
gra.addEdge('C','G')
gra.addEdge('D','G')
gra.addEdge('D','H')
gra.addEdge('B','E')
gra.addEdge('B','F')
console.log(gra.toSting())
//测试bfs
var result=''
gra.bfs(gra.vertexes[0],function(v){
result +=v+"_"
})
console.log(result)
//测试dfs
result=''
gra.dfs(gra.vertexes[0],function(v){
result +=v+"_"
})
console.log(result)
console.log(gra)
</script>
</body>
</html>