js --- Depth and breadth first traversal of graphs

Depth-first pass algorithm formula

  • Visit the root node
  • Depth-first traversal of the unvisited descending nodes of the root node
const graph = {
    0:[1,2],
    1:[2],
    2:[0,3],
    3:[3]
}
const visited = new Set()
const dfs = (n) =>{
    console.log(n)
    visited.add(n)
    graph[n].forEach(c => {
        if (!visited.has(c)){
            dfs(c)
        }
    });
}
dfs(2)//2  0  1  3 

Breadth-first traversal algorithm formula

  • Create a new queue and enqueue the root node
  • Depart the team and visit
  • The head of neighboring nodes not visited the team
  • Repeat the second and third steps until the queue is empty
const graph = {
    0: [1, 2],
    1: [2],
    2: [0, 3],
    3: [3]
}
const visited = new Set() //哈希表
visited.add(2)  // 起始点 先添加进验证是否访问过的哈希表
const q = [2]; // 起始点先入队 
while (q.length) {
    const n = q.shift(); // 出队 并访问
    console.log(n)   //  2 0 3 1 
    graph[n].forEach(c => {
        if (!visited.has(c)) {
            q.push(c) //没有访问过的节点 入队 
            visited.add(c); // 访问过的节点进入 哈希表
        }
    });
}

 

Guess you like

Origin blog.csdn.net/wanghongpu9305/article/details/111241878