广度优先算法
广度优先搜索(Breadth-First Search, BFS) 以广度为优先级,从起始顶点开始,逐层地向外扩展,先遍历当前节点的所有邻居节点,然后再遍历邻居节点的邻居节点,以此类推。 BFS 通常用于寻找最短路径或者在树或图中搜索目标
广度优先遍历(BFS):
// 树结构示例
const tree = {
value: "A",
children: [
{
value: "B",
children: [
{ value: "D", children: [] },
{ value: "E", children: [] },
],
},
{
value: "C",
children: [
{ value: "F", children: [] },
{ value: "G", children: [] },
],
},
],
};
// 广度优先遍历函数
function bfs(root) {
const queue = [root]; // 使用队列来存储待访问的节点
while (queue.length > 0) {
const node = queue.shift(); // 出队列
console.log(node.value); // 访问当前节点
node.children.forEach((child) => queue.push(child)); // 将当前节点的子节点入队列
}
}
// 执行广度优先遍历
bfs(tree);
在这两个示例中,tree 表示一个树结构,其中包含了多层嵌套的节点。深度优先遍历函数 dfs 采用递归的方式实现, 而广度优先遍历函数 bfs 则采用队列来存储待访问的节点,依