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
const Dictionary = require("./dictionary");
class Graph {
constructor() {
//存放图的订点
this.vertices = [];
//存放图的边
this.adjList = new Dictionary();
}
add(val) {
//判断vertices中是否存在这个订点, 不存在插入订点
if (!this.vertices.includes(val)) {
this.vertices.push(val);
this.adjList.add(val, []);
}
}
addEdge(a, b) {
// 如果图中没有顶点a,先添加顶点a
if (!this.adjList.has(a)) {
this.addVertex(a);
}
// 如果图中没有顶点b,先添加顶点b
if (!this.adjList.has(b)) {
this.addVertex(b);
}
this.adjList.find(a).push(b);
this.adjList.find(b).push(a);
}
getVertices() {
return this.vertices;
}
getAdjList() {
return this.adjList;
}
toString() {
// console.log(this.vertices);
// console.log(this.adjList);
let s = "";
this.vertices.forEach((v) => {
s += `${v} -> `;
this.adjList.find(v).forEach((n) => {
s += `${n} `;
});
s += "\n";
});
console.log(s);
}
}

// 初始化
const graph = new Graph();
const graphList = ["a", "b", "c", "d", "e"];
//设置访问的颜色
const Colors = {
//wei
WHITE: 0,
//fangwen
GREY: 1,
//tansuo
BLACK: 2,
};
//初始化一个图订点的颜色
let initializeColor = (vertices) => {
let color = {};
vertices.forEach((v) => (color[v] = Colors.WHITE));
return color;
};
graphList.forEach((key) => {
graph.add(key);
});

graph.addEdge("a", "b");
graph.addEdge("a", "e");
graph.addEdge("a", "d");
graph.addEdge("b", "c");
graph.addEdge("d", "e");
graph.addEdge("c", "a");
graph.toString();

const depthFirstSearch = function () {
const verticesList = graph.getVertices();
const adjList = graph.getAdjList();
const initColor = initializeColor(verticesList);
console.log(initColor);
};
depthFirstSearch();