concept
A graph is an abstract model of the network structure , a group of nodes connected by edges .
achieve
There are no graphs in JavaScript, but graphs are available Object
and Array
constructed.
Adjacency matrix
The above graph can be expressed as an adjacency matrix:
Adjacency list
The above figure can be expressed as an adjacency list:
const graph = {
A: ["B"],
B: ["C", "D"],
C: ["E"],
D: ["A"],
E: ["D"],
}
Traverse
As shown in the figure below, the starting point is 节点2
:
// start:2
const graph = {
0: [1, 2],
1: [2],
2: [0, 3],
3: [3]
};
Depth-first traversal
Search the branches of the graph as deeply as possible.
- Visit the root node
- The root node has not visited the adjacent nodes sequentially depth-first traversal
// 深度优先遍历图
// 已访问过的节点集合
const visited = new Set();
const dfs = n => {
console.log(n);
visited.add(n);
graph[n].forEach(c => {
if (!visited.has(c)) {
dfs(c);
}
});
};
Breadth first traversal
Visit the node closest to the root node first.
- Create a new queue, the root node joins the queue
- Head out and visit
- Team head has not visited the adjacent contacts into the team
- Repeat steps 2 and 3 until the queue is empty
const visited = new Set();
const q = [2];
// 起点先默认访问了
visited.add(2);
while (q.length) {
// 队头出队
const n = q.shift();
// 访问
console.log(n);
graph[n].forEach(c => {
if (!visited.has(c)) {
q.push(c);
// 入队就代表已经访问过了
visited.add(c);
}
});
}