JavaScript data structure-graph

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 Objectand Arrayconstructed.

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.

  1. Visit the root node
  2. 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.

  1. Create a new queue, the root node joins the queue
  2. Head out and visit
  3. Team head has not visited the adjacent contacts into the team
  4. 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);
        }
    });
}

Guess you like

Origin blog.csdn.net/Jack_lzx/article/details/114785383