-
Notifications
You must be signed in to change notification settings - Fork 1
/
graph.js
117 lines (98 loc) · 2.43 KB
/
graph.js
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
const Queue = require('./queue.js')
class Graph {
constructor () {
this.vertices = [] // 顶点集
this.edgesList = new Queue() // 边集
// ['A', 'B', 'c', 'd'] --- vertices
// A---> ['B', 'c', 'd']
// B---> ['c', 'd']
}
toString () {
let str = ''
for (let i = 0; i < this.vertices.length; i++) {
str += this.vertices[i] + '-->' + this.edgesList[this.vertices[i]] + '\n'
}
console.log(str)
}
// 添加顶点
addVertice (v) {
this.vertices.push(v)
this.edgesList[v] = []
}
// 添加边
addEdge (v1, v2) {
this.edgesList[v1].push(v2)
this.edgesList[v2].push(v1)
}
// 图的遍历
// 1.广度遍历 Breath-First-Search
BFS (initV, handler) {
const colors = this.initColors()
const queue = new Queue()
queue.enqueue(initV)
while (!queue.isEmpty()) {
const curV = queue.dequeue(initV)
colors[curV] = 'gray'
const vList = this.edgesList[curV]
for (let i = 0; i < vList.length; i++) {
const currentV = vList[i]
if (colors[currentV] === 'white') {
queue.enqueue(currentV)
colors[currentV] = 'gray'
}
}
handler(curV)
colors[curV] = 'black'
}
}
// 2.深度遍历 Depth-First-Search
DFS (initV, handler) {
const colors = this.initColors()
this.DFSNode(initV, colors, handler)
}
DFSNode (v, colors, handler) {
colors[v] = 'gray'
const vList = this.edgesList[v]
handler(v)
colors[v] = 'black'
for (let i = 0; i < vList.length; i++) {
const curV = vList[i]
if (colors[curV] === 'white') {
this.DFSNode(curV, colors, handler)
}
}
}
initColors () {
const colors = {}
for (let i = 0; i < this.vertices.length; i++) {
colors[this.vertices[i]] = 'white'
// 给每个顶点添加一个初始状态
}
return colors
}
}
const vertices = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
const graph = new Graph()
for (let i = 0; i < vertices.length; i++) {
graph.addVertice(vertices[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')
graph.toString()
function print () {
let str = ''
graph.DFS(graph.vertices[0], (v) => {
// console.log('v', v)
str += v + ' '
})
console.log(str)
}
print()