Greedy Best-First

Greedy Best-First pathfinding algorithm — interactive grid visualization, pseudocode in five languages, and complexity reference.

Time O((V + E) log V) Unweighted Heuristic Probabilistic

Implementation

function greedyPathfind(grid, start, end, allowDiag, hFn) {
  const h = hFn || HEURISTICS.manhattan;
  const visited = new Set([key(start[0], start[1])]);
  const prev = new Map();
  const heap = PriorityQueue("priority");
  priorityQueuePush(heap, {
    priority: h(start[0], start[1], end[0], end[1]),
    row: start[0],
    col: start[1]
  });
  while (priorityQueueSize(heap)) {
    const __pattern1 = priorityQueuePop(heap);
    const cr = __pattern1.row;
    const cc = __pattern1.col;
    visitNode(cr, cc);
    if (cr === end[0] && cc === end[1]) {
      reconstructPath(prev, start, end);
      return;
    }
    for (const [nr, nc] of getNeighbors(grid, cr, cc, allowDiag)) {
      const neighborKey = key(nr, nc);
      if (visited.has(neighborKey)) continue;
      visited.add(neighborKey);
      prev.set(neighborKey, [cr, cc]);
      priorityQueuePush(heap, {
        priority: h(nr, nc, end[0], end[1]),
        row: nr,
        col: nc
      });
      pushFrontier(nr, nc);
    }
  }
  reportNoPath();
}