JS中的DFS和BFS
Posted zhenfeishi
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS中的DFS和BFS相关的知识,希望对你有一定的参考价值。
示例对象:
{
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的主要内容,如果未能解决你的问题,请参考以下文章