⚡0 XP🔥0

Search Algorithms - BFS, DFS, UCS and A*

Lesson 3 of 8 ⏱ 7 min read ✎ 1 exercises ❓ 5-question quiz ▶ Runs Python

Solve problems by searching a state space - uninformed search (BFS, DFS, uniform-cost) and informed search with heuristics (greedy best-first, A*), compared on a map of Madhya Pradesh cities and on grid path-finding.

Many AI problems - route planning, puzzles, scheduling, robot motion - can be solved by searching: start in some state, try actions, and look for a sequence of actions that reaches a goal.

Formulating a search problem#

Part Route-planning example
States which city you are in
Initial state Indore
Actions drive along a road to a neighbouring city
Transition model taking road Indore→Dewas puts you in Dewas
Goal test are we in Jabalpur?
Path cost total kilometres

The states and actions form a graph (the state space). Search algorithms differ in which node they expand next.

Our simplified teaching map (approximate road distances in km; real roads have many more connections):

            Gwalior
               |
              420
               |
 Ujjain -55- Indore -35- Dewas -150- Bhopal -330- Jabalpur
    \                                  /
     \--190-- Shajapur ---180--------/
▶ Try it YourselfPython
Ctrl + Enter to run
Output
Indore    -> {'Ujjain': 55, 'Dewas': 35, 'Gwalior': 420}
Ujjain    -> {'Indore': 55, 'Shajapur': 190}
Dewas     -> {'Indore': 35, 'Bhopal': 150}
Shajapur  -> {'Ujjain': 190, 'Bhopal': 180}
Bhopal    -> {'Dewas': 150, 'Shajapur': 180, 'Jabalpur': 330}
Gwalior   -> {'Indore': 420}
Jabalpur  -> {'Bhopal': 330}

Breadth-first search (BFS)#

BFS expands the shallowest node first using a FIFO queue. It finds the path with the fewest steps (not necessarily the fewest kilometres).

▶ Try it YourselfPython
Ctrl + Enter to run
Output
BFS path: Indore -> Dewas -> Bhopal -> Jabalpur (3 roads, 515 km), expanded 6 cities

Depth-first search (DFS)#

DFS goes as deep as possible before backtracking, using a stack (or recursion). It uses little memory but may find a long path, and can get lost in infinite spaces without a depth limit.

▶ Try it YourselfPython
Ctrl + Enter to run
Output
  visiting Indore
  visiting Ujjain
  visiting Shajapur
  visiting Bhopal
  visiting Dewas
  visiting Jabalpur
DFS path: Indore -> Ujjain -> Shajapur -> Bhopal -> Jabalpur (755 km)

DFS wandered via Ujjain and Shajapur and found a longer route.

Uniform-cost search (UCS)#

UCS always expands the frontier node with the lowest path cost so far, g(n), using a priority queue. It finds the cheapest path (this is Dijkstra's algorithm).

▶ Try it YourselfPython
Ctrl + Enter to run
Output
UCS path: Indore -> Dewas -> Bhopal -> Jabalpur = 515 km, expanded 7 cities
हिंदी में समझें

BFS सबसे कम कदमों वाला रास्ता ढूँढता है, DFS गहराई में जाता है और कोई भी रास्ता दे सकता है, और UCS हमेशा अब तक की सबसे कम दूरी वाले शहर को पहले खोलता है - इसलिए यह सबसे छोटा (km में) रास्ता देता है। ये तीनों "uninformed" हैं: इन्हें नहीं पता कि goal किस तरफ़ है।

Informed search: heuristics and A*#

A heuristic h(n) is a cheap estimate of the remaining cost from n to the goal - for maps, the straight-line ("as the crow flies") distance. A* expands the node with the lowest

f(n) = g(n) + h(n)      (cost so far + estimated cost to go)

If h never overestimates (it is admissible), A* is guaranteed to find the cheapest path - usually after expanding far fewer nodes than UCS.

▶ Try it YourselfPython
Ctrl + Enter to run
Output
A* path: Indore -> Dewas -> Bhopal -> Jabalpur = 515 km
expanded in order: ['Indore', 'Dewas', 'Bhopal', 'Jabalpur']

A* found the same optimal route as UCS while ignoring Gwalior, which the heuristic shows is in the wrong direction.

Seeing the difference on a grid#

InteractiveBFS vs A* on a grid

Draw walls by clicking and dragging, then run BFS and A* and compare how many cells each explores before finding the shortest path. Both find a shortest path; A* explores far fewer cells because the heuristic pulls it toward the goal.

Comparison#

Algorithm Frontier Finds Notes
BFS queue fewest steps memory-hungry
DFS stack some path low memory, may be long, needs depth limit
UCS / Dijkstra priority queue on g cheapest path explores in all directions
Greedy best-first priority queue on h some path, fast not guaranteed optimal
A* priority queue on g + h cheapest path (admissible h) the standard for path-finding (maps, games, robots)
Tip

Google Maps, game characters finding their way around, and warehouse robots all use descendants of A* and Dijkstra, with clever heuristics and pre-computed shortcuts.

Summary#

  • Define states, actions, transition model, goal test and path cost; the state space is a graph.
  • BFS (fewest steps), DFS (deep first), UCS (cheapest) are uninformed.
  • A* uses f = g + h; with an admissible heuristic it finds the cheapest path while exploring less.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

BFS on a friendship graph

Using BFS, write degrees(graph, start, target) that returns the minimum number of hops between two people (or -1 if unreachable). Store degrees(friends, "Asha", "Zoya") in d and print it.

Quick Quiz

Q1.

BFS (breadth-first search) explores...

Q2.

DFS uses which data structure?

Q3.

In A*, f(n) = g(n) + h(n). What is h(n)?

Q4.

When is A* guaranteed to find the cheapest path?

Q5.

Uniform-cost search always expands...