码迷,mamicode.com
首页 > Web开发 > 详细

JS中的DFS和BFS

时间:2020-07-29 21:58:21      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:==   name   OLE   break   ++   let   深度   style   广度优先   

示例对象:
{
  name: ‘a‘,
  next: [
    {
      name: ‘b‘,
      next: [
        {
          name: ‘d‘,
          next: []
        },
        {
          name: ‘e‘,
          next: []
        }
      ]
    },
    {
      name: ‘c‘,
      next: [
        {
          name: ‘f‘,
          next: []
        },
        {
          name: ‘g‘,
          next: []
        }
      ]
    }
  ]
}
广度优先遍历:
function BFS(obj){
    let list = [obj],
        listTemp = [];
    while(list.length != 0){
      for(let i = 0, len = list.length; i < len; ++i){
        console.log(list[i].name);
        listTemp = [...listTemp, ...list[i].next];
      }
      list = listTemp;
      listTemp = [];
    }
}
深度优先遍历:
function DFS(obj){
    let p = obj,
        p_p = [],
        n = -1;
    while(p != null){
      if(p.is != true){
        console.log(p.name);
        p.is = true;
      }
      let pTemp = null;
      for(let i = 0, len = p.next.length; i < len; ++i){
        if(p.next[i].is != true){
          p_p[n + 1] = p;
          pTemp = p.next[i];
          ++n;
          break;
        }
      }
      p = pTemp;
      if(p == null){
        p = p_p[n];
        --n;
      }
    }
}

 

 
 

JS中的DFS和BFS

标签:==   name   OLE   break   ++   let   深度   style   广度优先   

原文地址:https://www.cnblogs.com/zhenfeishi/p/13399185.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!