Greedy Best first search algorithm (original) (raw)

Last Updated : 27 May, 2026

Greedy Best-First Search is an AI search algorithm used to find a path from a starting node to a goal node by selecting the path that appears most promising at each step. It uses heuristic values to guide the search toward the goal efficiently.

Working

Greedy Best-First Search works by selecting the node that appears closest to the goal using heuristic values and continues expanding the most promising path until the destination is reached.

greedy_best_first_search

Workflow of Greedy Best first Search Algorithm

Implementation

Let's implement the Greedy Best-First Search algorithm using a graph where heuristic values estimate the distance from each node to the goal node.

**Step 1: Importing the heapq module for priority queue operations and define the graph structure.

Python `

import heapq

graph = { 'A': [('B', 1), ('C', 1), ('D', 1)], 'B': [('E', 1), ('F', 1)], 'C': [('F', 1)], 'D': [('G', 1)], 'E': [('G', 1)], 'F': [('G', 1)], 'G': [] }

`

**Step 2: Now we assign heuristic values to each node representing estimated distance to the goal node.

Python `

heuristic = { 'A': 40, 'B': 32, 'C': 25, 'D': 35, 'E': 19, 'F': 17, 'G': 0 }

`

**Step 3: Creating a function that selects and expands the node with the lowest heuristic value until the goal node is reached.

Python `

def greedy_best_first_search(start, goal):

visited = set()
priority_queue = []

heapq.heappush(priority_queue, (heuristic[start], start, [start]))

while priority_queue:

    h, current, path = heapq.heappop(priority_queue)

    if current == goal:
        return path

    if current not in visited:
        visited.add(current)

        for neighbor, cost in graph[current]:
            if neighbor not in visited:
                heapq.heappush(
                    priority_queue,
                    (heuristic[neighbor], neighbor, path + [neighbor])
                )

return None

`

**Step 4: We call the function to find the path from node A to node G.

Python `

result = greedy_best_first_search('A', 'G')

print("Path found:", " -> ".join(result))

`

**Output:

Path found: A -> C -> F -> G

Advantages

Limitations

Applications