图为非线性数据结构
array[i][j] = 1
表示两个顶点之间有边,否则array[i][j] = 0
邻接矩阵的问题:如果图是稀疏图,矩阵中会存在大量的0,浪费了空间
数组、链表、字典、哈希表
存储都可以
邻接表的问题:计算有向图的入度
非常麻烦(入度:指向自己的数量,出度:指向别人的数量)
fucntion Graph() {
this.vertexes = []
this.edges = new Dictionary()
}
addVertex(v) {
this.vertexes.push(v)
this.edges.set(v, [])
}
addEdge(v1,v2) {
this.edges.get(v1).push(v2)
this.edges.get(v2).push(v1)
}
toString() {
let string = ''
for(let i = 0; i < this.vertexes.length; i++) {
string += this.edges.get(this.vertexes[i]) + '->'
let vEdges = this.edges.get(this.vertexes[i])
for(let j = 0; j < vEdges.length; j++) {
string += vEdges[j] + ''
}
string += '\n'
}
return string
}
let graph = new Graph()
let arr = ['A','B','C','D','E','F','G','H','I']
for (let i = 0; i < arr.length; i++) {
graph.addVertex(arr[i])
}
graph.addEdge('A', 'B')
graph.addEdge('A', 'C')
graph.addEdge('A', 'D')
graph.addEdge('C', 'D')
graph.addEdge('C', 'G')
graph.addEdge('D', 'G')
graph.addEdge('D', 'H')
graph.addEdge('B', 'E')
graph.addEdge('B', 'F')
graph.addEdge('E', 'I')
console.log(graph.toString())