Articles / AI · Part 18

Greedy Best-First Search in Artificial Intelligence

Learn how Greedy Best-First Search uses heuristic values and a priority queue to explore promising paths. Understand its Python implementation, working process, complexity, advantages, limitations, and differences from A* Search.

Greedy Best-First Search in Artificial Intelligence

Imagine you are trying to reach a destination in an unfamiliar city. You have several roads in front of you. Instead of considering the entire journey, you choose the road that appears to take you closest to your destination.

You reach another junction and make the same decision again.

At every step, you choose the option that looks most promising at that moment.

This is the basic idea behind Greedy Best-First Search.

In Artificial Intelligence, this algorithm uses a heuristic function to estimate how close a node is to the goal. It then prioritises the node with the lowest estimated remaining cost.

But there is an important question: does choosing what looks best at every step always lead to the best solution?

Let’s understand how the algorithm works.

Greedy Best-First Search (GBFS) is an informed search algorithm that selects the next node based on its estimated distance or cost to the goal.

It uses a heuristic function represented by:

\[
h(n)
\]

The algorithm chooses the node with the lowest heuristic value.

Its evaluation function is:

\[
f(n) = h(n)
\]

Here:

  • \(n\) represents a node.
  • \(h(n)\) estimates the remaining cost from that node to the goal.
  • \(f(n)\) determines the priority of the node.

The word greedy describes its decision-making approach. It focuses on the option that appears best immediately, without considering the complete cost already spent reaching that option.

2. How Does Greedy Best-First Search Work?

Consider this search tree:

                S
              /   \
             A     B
            /       \
           C         D

Suppose S is the starting node and D is the goal.

The heuristic values are:

Node Heuristic value
S 5
A 3
B 1
C 4
D 0

The algorithm begins at S.

Step 1: Explore S and examine its neighbours A and B.

  • A has \(h(A)=3\).
  • B has \(h(B)=1\).

Since B has the lower heuristic value, it is selected.

Step 2: Explore B. Its neighbour is D.

  • D has \(h(D)=0\).

The algorithm selects D and finds the goal.

The search path is:

\[
S \rightarrow B \rightarrow D
\]

The algorithm chooses B because it appears closer to the goal according to the heuristic.

3. The Role of a Priority Queue

Greedy Best-First Search commonly uses a Priority Queue to decide which node should be explored next.

A priority queue stores elements according to their priority. In this algorithm, nodes with smaller heuristic values receive higher priority.

For example:

Node Heuristic Priority
A 5 Lower
B 2 Higher
C 7 Lower

Node B will be selected first because it has the smallest heuristic value.

This is different from the ordinary queue used in Breadth-First Search, where nodes are generally processed in the order they were added.

4. Greedy Best-First Search Algorithm

The general steps are:

  1. Start with the initial node.
  2. Insert it into the priority queue.
  3. Remove the node with the lowest heuristic value.
  4. Check whether it is the goal.
  5. If it is the goal, return the solution.
  6. Otherwise, add its unvisited neighbours to the priority queue.
  7. Repeat until the goal is found or no nodes remain.

A visited set helps prevent repeated exploration of nodes in graphs containing cycles.

5. Implementing Greedy Best-First Search in Python

Let’s implement the algorithm using Python’s heapq module, which provides a priority queue.

We will use a simple graph where each node has a heuristic estimate.

import heapq

graph = {
    'S': ['A', 'B'],
    'A': ['C'],
    'B': ['D'],
    'C': [],
    'D': []
}

heuristic = {
    'S': 5,
    'A': 3,
    'B': 1,
    'C': 4,
    'D': 0
}

def greedy_best_first_search(start, goal):
    priority_queue = [(heuristic[start], start)]
    visited = set()

    while priority_queue:
        h, node = heapq.heappop(priority_queue)

        if node in visited:
            continue

        print("Exploring:", node)
        visited.add(node)

        if node == goal:
            return True

        for neighbour in graph[node]:
            if neighbour not in visited:
                heapq.heappush(
                    priority_queue,
                    (heuristic[neighbour], neighbour)
                )

    return False


print(greedy_best_first_search('S', 'D'))

Output:

Exploring: S
Exploring: B
Exploring: D
True

Let’s understand the important parts:

  • heapq manages the priority queue.
  • heuristic stores the estimated cost of each node to the goal.
  • heapq.heappop() removes the node with the lowest priority.
  • heapq.heappush() adds neighbouring nodes to the queue.
  • visited prevents the algorithm from repeatedly exploring the same node.

This example returns True when the goal is found. A path-finding implementation can additionally store parent information to reconstruct the route.

6. Why Is Greedy Best-First Search Not Always Optimal?

Greedy Best-First Search makes decisions using only the estimated remaining cost.

It does not consider how much it has already cost to reach a node.

This can cause problems.

Imagine two possible routes to a destination:

Route Cost already travelled Estimated remaining cost
Route A 2 10
Route B 20 1

Greedy Best-First Search prefers Route B because its estimated remaining cost is lower.

However, the total estimated costs are:

  • Route A: \(2 + 10 = 12\)
  • Route B: \(20 + 1 = 21\)

Route A is actually more promising when the cost already travelled is considered.

Greedy Best-First Search ignores that information.

This is why it does not guarantee the least-cost solution.

A* search addresses this limitation by considering both the cost already travelled and the estimated remaining cost.

Let’s examine its main properties.

Property Description
Search type Informed search
Evaluation function \(f(n)=h(n)\)
Data structure Priority queue
Completeness Not guaranteed in general; possible under finite-graph search with repeated-state handling
Optimality No
Time complexity \(O(b^m)\) in the general tree-search worst case
Space complexity \(O(b^m)\) in the general tree-search worst case

Here:

  • \(b\) is the branching factor.
  • \(m\) is the maximum depth of the search tree.

The complexity can vary with the search space and heuristic. In particular, the priority queue and the number of stored nodes affect practical memory use.

  • Uses heuristic knowledge: It makes decisions using estimates of how close nodes are to the goal.
  • Can find solutions quickly: A useful heuristic may guide it towards the goal without exploring many unnecessary nodes.
  • Easy to understand: Its central idea is simply to choose the node with the lowest heuristic value.
  • Useful for large search spaces: It can be effective when a good heuristic is available.
  • Not optimal: It does not guarantee the least-cost solution.
  • Depends on the heuristic: Poor estimates can lead the search in an unhelpful direction.
  • Can make locally attractive decisions: A node that looks close to the goal may lead to an expensive route.
  • Can use considerable memory: It may need to store many generated nodes in its priority queue.
  • Completeness depends on the search space and implementation: It is not guaranteed to find a solution in every possible search space.

Greedy Best-First Search can be useful in problems where quickly identifying promising options is important.

Some examples include:

  • Route finding: Prioritising locations that appear closer to a destination.
  • Robotics: Guiding a robot towards a target position.
  • Game search: Exploring moves that appear to bring a player closer to a goal.
  • Puzzle solving: Prioritising puzzle states that look closer to the solved state.
  • Planning: Exploring actions that appear to move a system towards a desired outcome.

Its effectiveness depends heavily on how accurately the heuristic represents progress towards the goal.

11. Greedy Best-First Search vs A*

Both algorithms use heuristic information, but their evaluation functions are different.

Feature Greedy Best-First Search A* Search
Evaluation function (f(n)=h(n)) (f(n)=g(n)+h(n))
Actual path cost Ignored Considered
Estimated remaining cost Considered Considered
Optimality Not guaranteed Guaranteed under standard conditions with an admissible heuristic and suitable graph-search handling
Main focus What appears closest to the goal Lowest estimated total path cost

The key difference is that Greedy Best-First Search considers only the estimated remaining cost, while A* also considers the cost already travelled.

Conclusion

Greedy Best-First Search demonstrates how heuristic knowledge can guide an AI system towards a goal.

By selecting the node that appears closest to the destination, it can sometimes find solutions quickly. However, a locally promising choice does not always lead to the best overall solution.

That is why the next algorithm is especially important.

In the next article, we will explore A Search*, which combines actual path cost and estimated remaining cost to make more informed decisions.

Quick quiz

5 questions
What does Greedy Best-First Search use to select the next node?
Which evaluation function does Greedy Best-First Search use?
Which data structure is commonly used in Greedy Best-First Search?
Why is Greedy Best-First Search not optimal?
What is the main difference between Greedy Best-First Search and A?*

Keep a copy

Read offline as a printout or PDF.

farhanpaal.com

Keep reading

AI · Part 15

Depth-First Search (DFS)

Learn how Depth-First Search explores a search tree by following one branch deeply before backtracking. Understand stacks, the DFS algorithm, Python implementation,…

7 min read
AI · Part 38

Reasoning in Fuzzy Logic

Understand how fuzzy reasoning works in Artificial Intelligence. Explore fuzzification, rule evaluation, aggregation, and defuzzification through a simple air-conditioning example.

4 min read
AI · Part 39

Mamdani Inference Method

Learn how the Mamdani Inference Method works through fuzzification, rule evaluation, aggregation, and defuzzification. Explore its applications and compare it with Sugeno…

3 min read

Ask Farhan

Ask anything about Farhan