SPFA (Queue BF)

SPFA (Queue BF) pathfinding algorithm — interactive grid visualization, pseudocode in five languages, and complexity reference.

Time O(E) average, O(V * E) worst case Weighted Informed

Implementation

function spfaPathfind(grid, start, end, allowDiag) {
  const rows = grid.length;
  const cols = grid[0].length;
  const dist = Matrix(rows, cols, Infinity);
  const inQueue = Matrix(rows, cols, false);
  const prev = new Map();
  const queue = [[start[0], start[1]]];
  dist[start[0]][start[1]] = 0;
  inQueue[start[0]][start[1]] = true;
  while (queue.length) {
    const __pattern1 = queue.shift();
    const r = __pattern1[0];
    const c = __pattern1[1];
    inQueue[r][c] = false;
    visitNode(r, c);
    for (const [nr, nc] of getNeighbors(grid, r, c, allowDiag)) {
      const nd = dist[r][c] + stepCost(grid, r, c, nr, nc);
      if (nd < dist[nr][nc]) {
        dist[nr][nc] = nd;
        prev.set(key(nr, nc), [r, c]);
        if (!inQueue[nr][nc]) {
          queue.push([nr, nc]);
          inQueue[nr][nc] = true;
          pushFrontier(nr, nc);
        }
      }
    }
  }
  if (dist[end[0]][end[1]] !== Infinity) {
    reconstructPath(prev, start, end);
  } else {
    reportNoPath();
  }
}