FlowLab Logo

Greedy Best-First Search Pathfinding

SlowFast
S
Start
E
End
Wall
Visited
Current
Path
Operation Logs
No operations yet
Algorithm Info
Time Complexity: O(E) for grid graphs, E = edges
Space Complexity: O(V) for open set and visited set
Optimal: No (may not find shortest path)
Complete: Yes (will find solution if one exists)
How it works: Uses only heuristic to select next cell, ignoring cost from start.
Best for: Fast approximate solutions, exploration, visualizations.
Heuristic: Manhattan distance (for grid graphs without diagonals)
Implementation
function greedyBestFirst(grid, start, end) {
  const openSet = [start];
  start.h = heuristic(start, end);

  while (openSet.length > 0) {
    // Find node in openSet with lowest h
    let current = openSet.reduce((a, b) => a.h < b.h ? a : b);

    if (current === end) {
      return reconstructPath(end);
    }

    openSet.splice(openSet.indexOf(current), 1);
    current.visited = true;

    for (const neighbor of getNeighbors(current)) {
      if (neighbor.wall || neighbor.visited) continue;
      const h = heuristic(neighbor, end);
      if (neighbor.h > h) {
        neighbor.parent = current;
        neighbor.h = h;
        openSet.push(neighbor);
      }
    }
  }
  return null;
}

function heuristic(a, b) {
  return Math.abs(a.row - b.row) + Math.abs(a.col - b.col);
}