Bellman-Ford

Bellman-Ford pathfinding algorithm — interactive grid visualization, pseudocode in five languages, and complexity reference.

Time O(V * E) Weighted Informed

Implementation

function bellmanfordPathfind(grid, start, end, allowDiag) {
  const rows = grid.length;
  const cols = grid[0].length;
  const dist = Matrix(rows, cols, Infinity);
  const prev = new Map();
  dist[start[0]][start[1]] = 0;
  const total = rows * cols;
  for (let iter = 0; iter < total - 1; iter++) {
    let updated = false;
    for (let r = 0; r < rows; r++) {
      for (let c = 0; c < cols; c++) {
        if (grid[r][c] === WALL || dist[r][c] === Infinity) continue;
        let relaxedHere = false;
        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]);
            updated = true;
            if (!relaxedHere) {
              visitNode(r, c);
              relaxedHere = true;
            }
            pushFrontier(nr, nc);
          }
        }
      }
    }
    if (!updated) break;
  }
  if (dist[end[0]][end[1]] !== Infinity) {
    reconstructPath(prev, start, end);
  } else {
    reportNoPath();
  }
}