图的深度优先遍历和广度优先遍历

x33g5p2x  于2022-03-11 转载在 其他  
字(0.7k)|赞(0)|评价(0)|浏览(424)

一、写在前面
图的深度优先遍历和广度优先遍历,也是我们必须要明白的算法。下面我们以有向图为了,来总结一下,图是如何做到深度优先遍历和广度优先遍历的。

使用数组表示如下所示

  1. let graph = {
  2. 0: [1, 2],
  3. 1: [2],
  4. 2: [0, 3],
  5. 3: [3]
  6. }

二、深度优先遍历

  1. const graph = require('./database')
  2. let set = new Set() //使用Set数据结构来保存已经访问了的node节点。
  3. const dfs = (node) => {
  4. console.log(node)
  5. set.add(node) //将访问好的node节点,放入set中
  6. graph[node].forEach(item => {
  7. if(!set.has(item)) { //如果当前节点没有被访问,则进行递归访问
  8. dfs(item)
  9. }
  10. })
  11. }
  12. dfs(2)
  13. //2 0 1 3

二、广度优先遍历

  1. const graph = require('./database')
  2. const bfs = (node) => {
  3. let set = new Set()
  4. let queue = [node]
  5. while(queue.length) {
  6. let cur = queue.shift()
  7. set.add(cur)
  8. console.log(cur)
  9. graph[cur].forEach(item => {
  10. if(!set.has(item)) {
  11. queue.push(item)
  12. }
  13. })
  14. }
  15. }
  16. bfs(2) //2031

下面代码为广度优先遍历,我们使用的数据结构是Set(集合)和queue的 数据结构。

相关文章