当前位置:首页 > JavaScript

js实现bfs

2026-02-01 00:32:00JavaScript

JavaScript 实现广度优先搜索(BFS)

广度优先搜索(BFS)是一种用于遍历或搜索树或图的算法,它从根节点开始,逐层访问所有相邻节点。以下是 JavaScript 实现 BFS 的几种常见方法。

基于队列的 BFS 实现

BFS 通常使用队列数据结构来实现,以下是针对树或图的通用实现方式。

树的 BFS 实现

假设树的节点结构如下:

js实现bfs

class TreeNode {
  constructor(val) {
    this.val = val;
    this.children = [];
  }
}

BFS 实现代码:

function bfsTree(root) {
  if (!root) return [];
  const queue = [root];
  const result = [];
  while (queue.length > 0) {
    const node = queue.shift();
    result.push(node.val);
    for (const child of node.children) {
      queue.push(child);
    }
  }
  return result;
}

图的 BFS 实现

对于图结构,需要使用一个 visited 集合来避免重复访问。

js实现bfs

function bfsGraph(startNode) {
  const queue = [startNode];
  const visited = new Set();
  visited.add(startNode);
  const result = [];
  while (queue.length > 0) {
    const node = queue.shift();
    result.push(node.val);
    for (const neighbor of node.neighbors) {
      if (!visited.has(neighbor)) {
        visited.add(neighbor);
        queue.push(neighbor);
      }
    }
  }
  return result;
}

处理层级信息

如果需要记录每一层的节点,可以通过以下方式实现:

function bfsWithLevels(root) {
  if (!root) return [];
  const queue = [root];
  const result = [];
  while (queue.length > 0) {
    const levelSize = queue.length;
    const currentLevel = [];
    for (let i = 0; i < levelSize; i++) {
      const node = queue.shift();
      currentLevel.push(node.val);
      for (const child of node.children) {
        queue.push(child);
      }
    }
    result.push(currentLevel);
  }
  return result;
}

应用场景示例

  1. 二叉树层级遍历
    对于二叉树,BFS 可以用于按层输出节点值:

    function levelOrder(root) {
      if (!root) return [];
      const queue = [root];
      const result = [];
      while (queue.length > 0) {
        const levelSize = queue.length;
        const level = [];
        for (let i = 0; i < levelSize; i++) {
          const node = queue.shift();
          level.push(node.val);
          if (node.left) queue.push(node.left);
          if (node.right) queue.push(node.right);
        }
        result.push(level);
      }
      return result;
    }
  2. 最短路径问题
    BFS 可以用于无权图的最短路径查找,例如网格中的最短路径:

    function shortestPath(grid, start, end) {
      const queue = [[start, 0]];
      const visited = new Set([start.toString()]);
      const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]];
      while (queue.length > 0) {
        const [[x, y], dist] = queue.shift();
        if (x === end[0] && y === end[1]) return dist;
        for (const [dx, dy] of directions) {
          const nx = x + dx, ny = y + dy;
          if (isValid(nx, ny, grid) && !visited.has([nx, ny].toString())) {
            visited.add([nx, ny].toString());
            queue.push([[nx, ny], dist + 1]);
          }
        }
      }
      return -1;
    }

注意事项

  • 对于图结构的 BFS,必须使用 visited 集合避免循环访问。
  • 队列操作的时间复杂度为 O(1),但 shift 方法在 JavaScript 中可能导致 O(n) 时间,可以使用索引优化。
  • 如果节点值需要特殊处理(如对象),需自定义比较逻辑或使用 Map 替代 Set

标签: jsbfs
分享给朋友:

相关文章

js实现防洪

js实现防洪

防抖(Debounce)实现 防抖的核心思想是在事件触发后延迟执行回调函数,若在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口调整等场景。 function debounce(f…

js实现游标

js实现游标

使用JavaScript实现游标 在JavaScript中,可以通过操作DOM元素的cursor样式属性来实现自定义游标效果。以下是几种常见的实现方法: 修改默认鼠标指针样式 通过CSS的curso…

js实现投球

js实现投球

实现投球动画的基本思路 使用JavaScript和CSS动画结合的方式模拟投球效果。核心是通过改变元素的位置、旋转和缩放属性,配合定时器或CSS过渡实现平滑动画。 创建基础HTML结构 <…

js实现视口

js实现视口

js实现视口检测的方法 使用JavaScript检测元素是否进入视口(viewport)可以通过Intersection Observer API或手动计算元素位置实现。以下是两种常见方法: Int…

js 实现递归

js 实现递归

递归的基本概念 递归是指函数直接或间接调用自身的过程。在JavaScript中,递归通常用于解决可以分解为相似子问题的问题,如阶乘、斐波那契数列、树形结构遍历等。 递归的实现要点 基线条件(Base…

js实现文件夹

js实现文件夹

使用JavaScript创建文件夹 在浏览器端的JavaScript中无法直接操作文件系统创建文件夹,这是出于安全考虑。但在Node.js环境中可以通过文件系统模块(fs)实现。 Node.js中使…