欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JS深度优先遍历和广度优先遍历

程序员文章站 2022-05-20 20:23:12
...

JS深度优先遍历和广度优先遍历

深度优先遍历 (DFS)

Depth First Search

(1)访问顶点v;
(2)依次从v的未被访问的邻接点出发,对图进行深度优先遍历;直至图中和v有路径相通的顶点都被访问;
(3)若此时图中尚有顶点未被访问,则从一个未被访问的顶点出发,重新进行深度优先遍历,直到图中所有顶点均被访问过为止。

递归实现深度遍历

通过递归实现深度优先遍历

let depth1 = (node, nodeList = []) => {
	//node不能为null
    if (node !== null) {
        nodeList.push(node)
        let children = node.children || []
        //如果children.length存在
        for (let i = 0; i < children.length; i++) {
        	//递归调用
            depth1(children[i], nodeList)
        }
    }
    return nodeList
}
// obj
let obj = { 
    children: [{ 
        index: 0, 
        children: [{ 
            index: 1, 
            children: [{ 
                index: 3 
            }] 
        }] 
    }, { 
        index: 4 
    }, { 
        index: 5, 
        children: [{ 
            index: 7, 
            children: [{ 
                index: 8 
            }] 
        }] 
    }, { 
        index: 6 
    }] 
}
depth1(obj)
(9) [{}, {}, {}, {}, {}, {}, {}, {}, {}]
	0: {children: Array(4)}
	1: {index: 0, children: Array(1)}
	2: {index: 1, children: Array(1)}
	3: {index: 3}
	4: {index: 4}
	5: {index: 5, children: Array(1)}
	6: {index: 7, children: Array(1)}
	7: {index: 8}
	8: {index: 6}
	length: 9
非递归实现
let deepTraversal3 = (node) => {
    let stack = []
    let nodes = []
    if (node) {
        stack.push(node)
        while (stack.length) {
        	//每次取最后一个
            let item = stack.pop()
            let children = item.children || []
            nodes.push(item)
            //判断children的长度
            for (let i = children.length - 1; i >= 0; i--) {
                stack.push(children[i])
            }
        }
    }
    return nodes
}

广度优先遍历(BFS)

Breadth First Search

宽度优先搜索算法(又称广度优先搜索)是最简便的图的搜索算法之一,这一算法也是很多重要的图的算法的原型。Dijkstra单源最短路径算法和Prim最小生成树算法都采用了和宽度优先搜索类似的思想。其别名又叫BFS,属于一种盲目搜寻法,目的是系统地展开并检查图中的所有节点,以找寻结果。换句话说,它并不考虑结果的可能位置,彻底地搜索整张图,直到找到结果为止。

JS实现
let breadth = (node) => {
    let nodes = []
    let stack = []
    if (node) {
        stack.push(node)
        while (stack.length) {
        	//取第一个
            let item = stack.shift()
            let children = item.children || []
            nodes.push(item)
            for (let i = 0; i < children.length; i++) {
                stack.push(children[i])
            }
        }
    }
    return nodes
}
breadth(obj)
(9) [{}, {}, {}, {}, {}, {}, {}, {}, {}]
	0: {children: Array(4)}
	1: {index: 0, children: Array(1)}
	2: {index: 4}
	3: {index: 5, children: Array(1)}
	4: {index: 6}
	5: {index: 1, children: Array(1)}
	6: {index: 7, children: Array(1)}
	7: {index: 3}
	8: {index: 8}
	length: 9