257 阅读1分钟

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

深度遍历

dfs.png

const dfs = (graph, head) => {
  const visited = new Set()
  const fn = node => {
    console.log(node)
    visited.add(node)
    graph[node].forEach(item => {
      if (!visited.has(item)) {
        fn(item)
      }
    })
  }
  return fn(head)
}

// 2, 0, 1, 3

广度遍历

bfs.png

const bfs = (graph, head) => {
  const visited = new Set([head])
  const queue = [head]
  while (queue.length) {
    const node = queue.shift()
    console.log(node)
    graph[node].forEach(item => {
      if (!visited.has(item)) {
        queue.push(item)
        visited.add(item)
      }
    })
  }
}

// 2, 0, 3, 1

leetcode

  • 65
  • 417
  • 133