关于javascript:图的深度与广度优先遍历

图构造

const graph = {
    0: [1, 2],
    1: [2, 4],
    2: [0, 3],
    3: [],
    4: []
}

  1. 深度优先

const dfs = (root) => {
    const visited = new Set()
    const fn = (n) => {
        console.log(n)
        visited.add(n)
        graph[n].forEach(c => {
            if (!visited.has(c)) {
                fn(c)
            }
        })
    }
    fn(root)
}

dfs(0)

  1. 广度优先
const bfs = (root) => {
    const visited = new Set()
    const q = [root]
    visited.add(root)
    while(q.length) {
        const n = q.shift()
        console.log(n)
        graph[n].forEach(c => {
            if (!visited.has(c)) {
                q.push(c)
                visited.add(c)
            }
        })
    }

}
bfs(0)

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理