#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Home / Blog /

Best-First Search Algorithm in AI

Heuristic Search with Pathfinding Example

Published
5 min read
Scroll Down

What is best-first search?

Best-first search is an informed search strategy that, at every step, expands the node on the frontier that an evaluation function f(n) rates as most promising. It combines the advantages of breadth-first and depth-first search: like DFS it can follow one promising path deep without expanding everything, and like BFS it can switch to another branch when that path stops looking good.

The name covers a family of algorithms that differ only in f(n):

  • Greedy best-first search: f(n) = h(n), the estimated cost from n to the goal. It expands whichever node seems closest to the goal. When people say "best-first search" in an exam answer, this is usually the algorithm they mean.
  • A* search: f(n) = g(n) + h(n), adding the cost already paid to reach n.
  • Uniform-cost search: f(n) = g(n), with no heuristic at all.

Best-first search algorithm (OPEN and CLOSED lists)

The version below follows Rich and Knight's Artificial Intelligence. OPEN holds nodes that have been generated but not yet expanded, kept in order of f; CLOSED holds nodes already expanded.

  1. Put the start node on OPEN.
  2. Until a goal is found or OPEN is empty:
    • Pick the best node on OPEN (lowest f) and move it to CLOSED.
    • If it is a goal, stop and return the path to it.
    • Otherwise generate its successors. For each successor that is not on OPEN or CLOSED, evaluate it, record its parent and add it to OPEN. If a successor is already on OPEN, and the new path to it is better, update its parent.
  3. If OPEN becomes empty, report failure.

Compared with plain BFS, the only change is that OPEN is a priority queue ordered by f(n) instead of a first-in, first-out queue.

Worked example: route finding

Find a route from Arad to Bucharest on the Romania road map used throughout Russell and Norvig's Artificial Intelligence: A Modern Approach. The heuristic h(n) is the straight-line distance from each city to Bucharest.

Cityh(n): straight-line distance to Bucharest (km)
Arad366
Sibiu253
Timisoara329
Zerind374
Fagaras176
Rimnicu Vilcea193
Oradea380
Pitesti100
Bucharest0

Greedy best-first trace

StepExpandNew nodes on OPEN (h)Best on OPEN next
1AradSibiu (253), Timisoara (329), Zerind (374)Sibiu
2SibiuFagaras (176), Rimnicu Vilcea (193), Oradea (380)Fagaras
3FagarasBucharest (0)Bucharest
4Bucharestgoal reached-

Greedy best-first search finds the route Arad → Sibiu → Fagaras → Bucharest after expanding only four nodes. But the road distance is 140 + 99 + 211 = 450 km. The route through Rimnicu Vilcea and Pitesti is 140 + 80 + 97 + 101 = 418 km. Greedy search chose Fagaras because it looked closer in a straight line, without counting how far it had already travelled.

Best-first search in Python

One function handles both variants; only the evaluation function f changes. Stale queue entries are skipped when popped, which is the simplest way to implement OPEN with Python's heapq.

import heapq

roads = {
    'Arad': {'Sibiu': 140, 'Timisoara': 118, 'Zerind': 75},
    'Zerind': {'Arad': 75, 'Oradea': 71},
    'Oradea': {'Zerind': 71, 'Sibiu': 151},
    'Timisoara': {'Arad': 118, 'Lugoj': 111},
    'Lugoj': {'Timisoara': 111},
    'Sibiu': {'Arad': 140, 'Oradea': 151, 'Fagaras': 99, 'Rimnicu Vilcea': 80},
    'Fagaras': {'Sibiu': 99, 'Bucharest': 211},
    'Rimnicu Vilcea': {'Sibiu': 80, 'Pitesti': 97, 'Craiova': 146},
    'Pitesti': {'Rimnicu Vilcea': 97, 'Craiova': 138, 'Bucharest': 101},
    'Craiova': {'Rimnicu Vilcea': 146, 'Pitesti': 138},
    'Bucharest': {'Fagaras': 211, 'Pitesti': 101},
}
# straight-line distance to Bucharest (the heuristic h)
sld = {'Arad': 366, 'Zerind': 374, 'Oradea': 380, 'Timisoara': 329, 'Lugoj': 244,
       'Sibiu': 253, 'Fagaras': 176, 'Rimnicu Vilcea': 193, 'Pitesti': 100,
       'Craiova': 160, 'Bucharest': 0}

def best_first(start, goal, f):
    """Expand the OPEN node with the lowest f(g, node). Returns path, cost, expansion order."""
    open_list = [(f(0, start), 0, start, [start])]
    closed, order = set(), []
    while open_list:
        _, g, node, path = heapq.heappop(open_list)
        if node in closed:
            continue
        order.append(node)
        if node == goal:
            return path, g, order
        closed.add(node)
        for nxt, dist in roads[node].items():
            if nxt not in closed:
                heapq.heappush(open_list, (f(g + dist, nxt), g + dist, nxt, path + [nxt]))
    return None, None, order

greedy = best_first('Arad', 'Bucharest', lambda g, n: sld[n])          # f(n) = h(n)
astar = best_first('Arad', 'Bucharest', lambda g, n: g + sld[n])       # f(n) = g(n) + h(n)
for name, (path, cost, order) in [("Greedy best-first", greedy), ("A*", astar)]:
    print(f"{name}: {' -> '.join(path)} (cost {cost})")
    print(f"   expanded: {', '.join(order)}")

Output:

Greedy best-first: Arad -> Sibiu -> Fagaras -> Bucharest (cost 450)
   expanded: Arad, Sibiu, Fagaras, Bucharest
A*: Arad -> Sibiu -> Rimnicu Vilcea -> Pitesti -> Bucharest (cost 418)
   expanded: Arad, Sibiu, Rimnicu Vilcea, Fagaras, Pitesti, Bucharest

Greedy best-first is fast but returns the 450 km route. A* expands two more cities (Rimnicu Vilcea and Pitesti) and returns the shortest route, 418 km. That trade-off, fewer expansions against a better answer, is the main difference between the two. See the A* algorithm for why adding g(n) makes it optimal.

Properties of greedy best-first search

  • Not optimal: as the example shows, the first path it finds may be longer than the best one.
  • Not complete in general: without a CLOSED list it can loop forever (for example, going back and forth between two cities that both look close to the goal). With a CLOSED list it is complete on finite graphs.
  • Time and space: O(bm) in the worst case, where m is the maximum depth, because a misleading heuristic can send it the wrong way. A good heuristic reduces this dramatically in practice.
  • Depends entirely on h(n): a perfect heuristic leads it straight to the goal; a poor one can make it worse than uninformed search.
PointGreedy best-firstA*
Evaluation functionf(n) = h(n)f(n) = g(n) + h(n)
Optimal?NoYes, with an admissible h
Nodes expandedUsually fewerUsually more
Good forA quick, good-enough pathThe cheapest path

Where best-first search is used

  • Route planning and games, when a quick path is more important than the shortest one.
  • Puzzles such as the 8-puzzle with the number of misplaced tiles or Manhattan distance as h(n).
  • Web crawlers that visit the pages that look most relevant first (focused crawling).
  • As a building block: beam search keeps only the best k nodes on OPEN, trading completeness for memory.

Best-first search is one of several heuristic search techniques; hill climbing is the extreme case that keeps only one node instead of an OPEN list, and the AO* algorithm extends best-first search to AND-OR graphs. Informed search is part of Uncodemy's Artificial Intelligence course.