JS中的DFS和BFS

2021-01-15 04:13

阅读:528

标签:==   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 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 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


评论


亲,登录后才可以留言!