Search

Chapter Roadmap Define the Problem Abstraction, states, actions, goals, and costs Find a Solution Uninformed, informed, local, and constraint-based search Compe

2
Chapter 1: Search Roadmap
Define the Problem Abstraction, states, actions, goals, and costs
Find a Solution Uninformed, informed, local, and constraint-based search
Compete Against an Opponent Minimax, pruning, and uncertainty

Search Looks Ahead: Which Actions Reach the Goal?

Search Looks Ahead: Which Actions Reach the Goal?
3
Google Shape;37;p3

To Look Ahead, Build a Simpler Model

4
To Look Ahead, Build a Simpler Model
Real World Search Model
A robot turning the complex real world into a simpler puzzle-like model
Abstraction keeps only what the decision needs
States · Actions · Goal · Costs

Choose the Search Strategy to Match the Problem

5
Choose the Search Strategy to Match the Problem
No Guidance Uninformed Search
A Helpful Estimate Informed Search
Improve One Current State Local Search
Hard Constraints Constraint Satisfaction
An Opponent Adversarial Search

Defining a Search Problem

6
Defining a Search Problem
State Representation What information describes a situation?
Initial State Where does the agent begin?
Actions and Transition Model What can the agent do, and what changes?
Goal Test How do we recognise success?
Path Cost How do we compare solutions?
A solution is a sequence of actions from the initial state to a goal state

N-Queens Definition A: Place Anywhere, Check at the End

7
N-Queens Definition A: Place Anywhere, Check at the End
Start Empty board
Action Add a queen to any empty square
State Any arrangement of 0–n queens
Goal n queens, none attacking
Attacking partial boards are still states
Source

N-Queens Definition B: Rule Out Bad States Early

8
N-Queens Definition B: Rule Out Bad States Early
Start Empty board
Action Add one non-attacking queen to an empty column
State One queen per column, none attacking
Goal n queens on the board
Invalid partial boards never enter the state space

A State Space Contains Every Reachable State

9
A State Space Contains Every Reachable State
Different problem definitions produce different state spaces
TASK
Which definition has the larger state space?
Definition A Place anywhere. Check at the end.
Definition B Rule out bad states early.

Same Puzzle, Very Different State Spaces

10
Same Puzzle, Very Different State Spaces
SOLUTION
Definition A · Count Every Placement

|SA|=∑k=08(64k) |S_A| = \sum_{k=0}^{8} \binom{64}{k}

Definition B · Keep Only Safe Placements

|SB|=? |S_B| = ?

|SA|≈43,126×|SB| |S_A| \approx 43{,}126 \times |S_B|

A Search Tree Records Action Sequences

11
A Search Tree Records Action Sequences
State Space Graph
Each distinct state appears once
Search Tree
Each action sequence creates a tree node
S A B G S A B G G
Different paths to G create different search-tree nodes

Draw the Search Tree

12
Draw the Search Tree
Starting at S, draw the complete search tree. How many times does G appear?
TASK
State Space Graph
Search Tree
SOLUTION
S A B C G S A B C C G G G
G appears three times because three action sequences reach it
Trace the Search Tree
How many times does G appear in the complete search tree?
TASK
Cyclic State Space Graph
Search Tree Prefix
SOLUTION
S A B G S A B G B A G ⋮ ⋮
Infinitely many: A and B can alternate any number of times before moving to G

Define the Romania Route Problem

13
Define the Romania Route Problem
Find a route from Arad to Bucharest
TASK
SOLUTION
Map of Romania showing Arad and Bucharest
StateCurrent city
StartArad
Actions and TransitionChoose a neighboring city and move there
GoalReach Bucharest
Path CostSum of road distances
Source

Romania as a State-Space Graph

14
Romania as a State-Space Graph
Cities are states · roads are transitions · distances are step costs (ignored for now)
Weighted state space graph for the Romania route problem
Source

Expanding A Generates Three Successors

15
Expanding A Generates Three Successors
Western portion of the weighted Romania state space graph around Arad
Source

The Frontier Stores Nodes Waiting to Be Expanded

16
The Frontier Stores Nodes Waiting to Be Expanded
Frontier = generated nodes waiting to be expanded. It is the search algorithm’s current set of choices.
Initially: one generated node Frontier A select + remove Frontier after selection Frontier empty Expand A A select + remove add successors Before selection Frontier A Expand A A After expanding A Frontier S T Z
Which node should be expanded next: S, T, or Z?

A Search Strategy Chooses the Next Node to Expand

17
A Search Strategy Chooses the Next Node to Expand
It is the rule that determines the order of node expansion.
apply the selection rule Frontier S T Z Next node to expand ?
How should we compare search strategies?

Four Questions Compare Search Strategies

18
Four Questions Compare Search Strategies
We compare what a strategy guarantees and what resources it requires.
Completeness Will it find a solution whenever one exists?
Optimality Will it find a least-cost solution?
Time How many nodes are generated?
Space What is the maximum number of nodes held in memory?

Search Complexity Depends on b, d, and m

19
Search Complexity Depends on b, d, and m
S A B C D E F G H I J d = 2 m = 4
b = 3 maximum branching factor
d = 2 depth of the shallowest goal
m = 4 maximum path length

Search Repeats: Select, Test, Expand

20
Frontier S Select and remove Goal? yes solution no Expand generate successors add successors to the frontier empty → failure
The search strategy supplies the rule used at Select.

One Strategy, Two Search Algorithms

22
One Strategy, Two Search Algorithms
The strategy orders the frontier; TSA and GSA handle repeated states differently.
Tree Search Algorithm (TSA) Keeps a new search node for every path Graph Search Algorithm (GSA) Remembers explored states and can skip repeats S A B C C State C appears in two search nodes S A B C A node with explored state C can be skipped
We begin with BFS-TSA.

BFS Explores One Depth at a Time

23
BFS Explores One Depth at a Time
BFS uses a FIFO frontier: earlier nodes stay ahead of newly generated nodes.
Which node should be expanded next?
TASK
SOLUTION
depth 0 depth 1 depth 2 FIFO frontier S next S A B C next A B C D E next B C D E F G next C D E F G next C C
C is next: it entered the frontier at depth 1 before D, E, F, and G.

Python’s deque Implements a FIFO Frontier

24
Frontier front back A append("A") B append("B") C append("C") removed A front back B C popleft() → "A"; frontier = [B, C]

A Search Node Stores the Path So Far

25
A Search Node Stores the Path So Far
For our lecture code, a path string records one route through the search tree.
S a c b d G e
'S' → 'Sa' → 'Sab' → 'SabG'
path[-1] gives 'b'
path[-1] gives 'G'
search treemany possible routes
pathone route
current statelast character

BFS-TSA Repeats Three Operations

26
BFS-TSA Repeats
Three Operations
Remove the next path
Frontier['A'] -> []
Path'A'
Test its final state
Frontier[]
Goal testA ≠ B
Append every extension
Frontier[] -> ['AS', 'AT', 'AZ']
Romania road map with cities and road distances

What Happens When a Path Returns to A?

27
Program Output
A -> ['AS', 'AT', 'AZ']
AS -> ['AT', 'AZ', 'ASA', 'ASF',
'ASO', 'ASR']
AT -> ['AZ', 'ASA', 'ASF', 'ASO',
'ASR', 'ATA', 'ATL']
AZ -> ['ASA', 'ASF', 'ASO', 'ASR',
'ATA', 'ATL', 'AZA', 'AZO']
Search Tree
A S T Z A F O R A L A O
Explore A again?

TSA Repeats States Because It Has No Memory

28
PROBLEMTSA revisits states
It does not remember where it has been
A S A expanded expanded expand again?
SOLUTION Remember explored states explored = {'A', 'S'} A ∈ explored → skip
TSA+explored states=GSA
Repeated states are skipped instead of expanded again

BFS-GSA Remembers Explored States

29
Frontier['AS','AT','AZ']stores path strings
Explored{'A'}stores states only
Create the memoryexplored = set()
Skip a repeated statestate in explored
Remember before expandingexplored.add(state)

Romania State-Space Graph

30
Romania road map with cities and road distances

Run BFS-GSA on Romania

31
Romania state-space graph
frontier: pathsexplored: states
Source

BFS-GSA Practice

32
BFS-GSA Practice
TASK
S a d b e c G
Run BFS-GSA from S to G
RecordExplored orderReturned path
Add successors alphabetically
SOLUTION
S -> ['Sa', 'Sd', 'SG']
explored: ['S']
Sa -> ['Sd', 'SG', 'Sab']
explored: ['S', 'a']
Sd -> ['SG', 'Sab', 'Sdb', 'Sde']
explored: ['S', 'a', 'd']
solution: SG
Explored S → a → d Path S → G

Run the BFS-GSA Practice Code

BFS-TSA Properties

34
BFS-TSA Properties
TASK
Complete?
Optimal?
Time complexity?
Space complexity?
SOLUTION
Yes
Nounless all step costs are equal
O(bd+1) =* O(bd)
O(bd+1) =* O(bd)
b maximum branching factor d depth of the shallowest solution *If we treat b as fixed
01234 S G ⋯ ⋯⋯ ⋯⋯⋯⋯ ⋯⋯⋯⋯⋯
Assume b = 10, 1 million nodes/second, 1000 bytes/node
Depth Nodes Time Memory
2 110 0.11 milliseconds 110 kilobytes
4 11,110 11 milliseconds 11 megabytes
6 1.11 × 106 1.1 seconds 1.1 gigabytes
8 1.11 × 108 1.9 minutes 111 gigabytes
10 1.11 × 1010 3.1 hours 11 terabytes
12 1.11 × 1012 12.9 days 1.1 petabytes
14 1.11 × 1014 3.5 years 111 petabytes
16 1.11 × 1016 352 years 11 exabytes

BFS Explores the Shallowest Node First

BFS Explores the Shallowest Node First
35
Breadth-first search explores a search space one shallow layer at a time

frontier is a queue (first in first out data structure)

DFS Explores the Deepest Node First

DFS Explores the Deepest Node First
36
Google Shape;393;p33

frontier is a stack (last in first out data structure)

Python’s deque Implements a LIFO Frontier

37
Frontier bottom top A append("A") B append("B") C append("C") bottom top A B removed C pop() → "C"; frontier = [A, B]

Run DFS-GSA on Romania

38
Romania state-space graph
frontier: pathsexplored: states

DFS-GSA Follows the Newest Path

39
Program Output
A -> ['AS', 'AT', 'AZ']
explored: ['A']
AZ -> [..., 'AZA', 'AZO']
explored: ['A', 'Z']
AZO -> [..., 'AZOS', 'AZOZ']
explored: ['A', 'O', 'Z']
AZOS -> [..., 'AZOSR']
explored: ['A', 'O', 'S', 'Z']
Search Tree
A S T Z A O S Z
Romania state-space graph
LIFO follows the newest path.

DFS-GSA Practice

40
DFS-GSA Practice
TASK
S a d b e c G
Run DFS-GSA from S to G
RecordExplored orderReturned path
Add successors alphabetically
SOLUTION
S -> ['Sa', 'Sd', 'SG']
explored: ['S']
solution: SG
Explored S Path S → G

Run the DFS-GSA Practice Code

DFS-TSA Properties

42
DFS-TSA Properties
TASK
Complete?
Optimal?
Time complexity?
Space complexity?
SOLUTION
Nounless the search tree is finite
No
O(bm)
O(bm)
b maximum branching factor m maximum search-tree depth
012⋮m S G G ⋯⋯⋯⋯ newest path

BFS vs. DFS

43
BFS vs. DFS
TASK
SOLUTION
BFS
When can it outperform DFS?

When a solution is shallow

DFS
When can it outperform BFS?

When a solution lies deep along an early branch

TSA vs. GSA

44
TSA vs. GSA
TSA GSA
Memory Frontier Frontier + explored set
Repeated state Expand it again Skip it
Trade-off Less memory Fewer repeated expansions
BFS, DFS, and UCS can each use either algorithm

UCS Explores the Cheapest Node First

UCS Explores the Cheapest Node First
45
Miners explore a mountain containing rewards at different accumulated costs

frontier is a priority queue (smallest total path cost first)

A Priority Queue Removes the Cheapest Path

46
Frontier smallest total path cost first AS140 heappush(frontier,(140,"AS")) AT118 heappush(frontier,(118,"AT")) AZ75 heappush(frontier,(75,"AZ")) AT118 AS140 AZ75 removed first heappop(frontier)returns (75, "AZ")

Run UCS-GSA on Romania

47
Romania state-space graph with road distances
frontier: (cost, path)explored: states

UCS-GSA Follows the Cheapest Path

48
Program Output
A @ 0 -> [(75, 'AZ'), (118, 'AT'), (140, 'AS')]
explored: ['A']
AZ @ 75 -> [(118, 'AT'), (140, 'AS'), ...]
explored: ['A', 'Z']
AT @ 118 -> [(140, 'AS'), (146, 'AZO'), ...]
explored: ['A', 'T', 'Z']
AS @ 140 -> [(146, 'AZO'), (150, 'AZA'), ...]
explored: ['A', 'S', 'T', 'Z']
AZO @ 146 -> [(150, 'AZA'), (217, 'AZOZ'), ...]
explored: ['A', 'O', 'S', 'T', 'Z']
Search Tree
A S140 T118 Z75 A150 O146 A236 L229 A280 F239 O291 R220 S297 Z217
Romania state-space graph with road costs
Next path = smallest total path cost

UCS-GSA Practice

49
UCS-GSA Practice
TASK
SOLUTION
32105214143 S ad be cG
Run UCS-GSA from S to G
RecordExplored orderReturned path and cost
Add successors alphabetically
S @ 0 -> [(2, 'Sd'), (3, 'Sa'), (10, 'SG')]
explored: ['S']
Sd @ 2 -> [(3, 'Sa'), (3, 'Sdb'), (6, 'Sde'), (10, 'SG')]
explored: ['S', 'd']
Sa @ 3 -> [(3, 'Sdb'), (6, 'Sde'), (8, 'Sab'), (10, 'SG')]
explored: ['S', 'a', 'd']
Sdb @ 3 -> [(4, 'Sdbe'), (5, 'Sdbc'), (6, 'Sde'), (8, 'Sab'), (10, 'SG')]
explored: ['S', 'a', 'b', 'd']
Sdbe @ 4 -> [(5, 'Sdbc'), (6, 'Sde'), (7, 'SdbeG'), (8, 'Sab'), (10, 'SG')]
explored: ['S', 'a', 'b', 'd', 'e']
Sdbc @ 5 -> [(6, 'Sde'), (7, 'SdbeG'), (8, 'Sab'), (9, 'SdbcG'), (10, 'SG')]
explored: ['S', 'a', 'b', 'c', 'd', 'e']
Solution (7, 'SdbeG')Explored S → d → a → b → e → cPath S → d → b → e → G

Run the UCS-GSA Practice Code

UCS-TSA Properties

51
UCS-TSA Properties
TASK
Complete?
Optimal?
Time complexity?
Space complexity?
SOLUTION
Yes, iffinite b; c ≥ ε > 0
Yesgoal test on removal

O(b⌊C*/ε⌋+1) \mathrm{O}\!\left(b^{\left\lfloor C^*/\varepsilon \right\rfloor+1}\right)

O(b⌊C*/ε⌋+1) \mathrm{O}\!\left(b^{\left\lfloor C^*/\varepsilon \right\rfloor+1}\right)

Optimality allows c ≥ 0; completeness requires c ≥ ε > 0
C∗ cost of an optimal solutionε smallest positive step cost
S G C∗ UCS expands paths in increasing g(path), up to C∗

Uninformed Search Strategies

52
Uninformed Search Strategies
Strategy Frontier Next path Optimal?
BFS FIFO queue Shallowest Only with equal step costs
DFS LIFO stack Deepest No
UCS Priority queue Cheapest Yes
UCS uses only costs already incurred: g(path)

A Heuristic Estimates the Remaining Cost

A Heuristic Estimates the Remaining Cost
54
How far is a node from the goal?
AZOSTLMDCRFPBGUHEVIN
h(n): Estimated cost of the cheapest path from the state at node n to a goal
Straight-line distance to B
h(A) = 366 km
An estimate, not a road route
h(B) = 0
Use the estimate to guide which frontier node to explore next

Greedy Search Selects the Lowest h(n)

Greedy Search Selects the Lowest h(n)
55
Expand the frontier node estimated closest to the goal
ASTZ
Frontier after expanding A
Priority queue · smallest h first
Path Priority
AS h(S) = 253
AT h(T) = 329
AZ h(Z) = 374
Remove AS; explore S next
Greedy uses the estimated cost remaining; UCS uses the cost so far

Greedy Follows the Heuristic

Greedy Follows the Heuristic
56
Select the frontier node with the smallest h(n)
Original Greedy Follows the Heuristic mining illustration
Source: UC Berkeley CS188

Greedy-GSA Follows the Smallest Estimate

57
Search Trace · @ = h(final state)
A @ 366 →
[(253, 'AS'), (329, 'AT'), (374, 'AZ')]
explored: ['A']
AS @ 253 →
[(176, 'ASF'), (193, 'ASR'), ...]
explored: ['A', 'S']
ASF @ 176 →
[(0, 'ASFB'), (193, 'ASR'), ...]
explored: ['A', 'F', 'S']
ASFB @ 0 → goal B
solution: ASFB
Search Tree
Ah=366Sh=253Th=329Zh=374Ah=366Fh=176Oh=380Rh=193Bh=0Sh=253

Greedy Search Is Not Always Optimal

Greedy Search Is Not Always Optimal
58
Greedy · ASFB
14099211ASFB
140 + 99 + 211 = 450
UCS · ASRPB
1408097101ASRPB
140 + 80 + 97 + 101 = 418
A smaller h-value does not guarantee a cheaper complete path

Greedy-TSA Practice

Greedy-TSA Practice
59
32105141243Sh=7ah=9bh=4ch=2dh=5eh=3Gh=0

Start: S   ·   Goal: G

Which states are expanded?
Which path is returned? Is it the cheapest?

Initial frontier: [(7, 'S')]

Exploring: S at h = 7
Frontier:
[(0, 'SG'), (5, 'Sd'), (9, 'Sa')]
Solution path: SG

A* Motivation: UCS

A* Motivation: UCS
60
Cheap so far can still lead away from the goal
1138121Sh=6ah=5bh=6ch=7eh=1dh=2Gh=0

After expanding a

Sab: g=2
Sad: g=4
Sae: g=9

Follow the cheap branch

Sab → Sabc
c is a dead end

Return to the waiting path

Sad → SadG
Solution cost: 6

The Tortoise and the Hare

The Tortoise and the Hare
62
The original tortoise comic
UCS
Cost so far
The original running hare comic
Greedy
Estimated cost remaining
Can we combine their strengths?
The tortoise rides on the running hare
A*
Use both costs
Source: UC Berkeley CS188

A* Combines Cost So Far and Cost Remaining

A* Combines Cost So Far and Cost Remaining
63
g(n) + h(n) = f(n)
A S B
Cost so far
Actual path cost from A to S
Estimated cost remaining
Heuristic estimate from S to B
Node n represents path AS
Select the frontier node with the smallest f(n)

A* Motivation: Combine Both Costs

A* Motivation: Combine Both Costs
64
Now revisit the same choices using g + h
1138121Sh=6ah=5bh=6ch=7eh=1dh=2Gh=0

After expanding a

Sab: 2 + 6 = 8
Sad: 4 + 2 = 6
Sae: 9 + 1 = 10

Select Sad

Its estimated total cost is smallest
SadG: 6 + 0 = 6

Reach G without either detour

Expanded: S → a → d
Returned path: SadG, cost 6

A* Uses Both Costs

A* Uses Both Costs
65
Select the frontier node with the smallest g(n) + h(n)
Original A* Uses Both Costs mining illustration
Source: UC Berkeley CS188

A*-TSA Code

A* Selects the Smallest g + h

A* Selects the Smallest g + h
67
Same frontier paths · a new priority
ASTZ
Frontier after expanding A
g: path cost · h: estimate at final state
Path g h f = g + h
AS 140 253 393
AT 118 329 447
AZ 75 374 449
Remove AS: 393 is smallest

A* Keeps Comparing Frontier Paths

A* Keeps Comparing Frontier Paths
68
Which path leaves the frontier next?
ASRFPBBf=450f=418
Expanded path f Two lowest frontier priorities
A 366 AS: 393 · AT: 447
AS 393 ASR: 413 · ASF: 415
ASR 413 ASF: 415 · ASRP: 417
ASF 415 ASRP: 417 · AT: 447
ASRP 417 ASRPB: 418 · AT: 447
ASRPB: g=418, h(B)=0, f=418
Remove ASRPB and stop
Solution cost: 418
Tree shows the competing routes
Other generated branches are omitted

A*-TSA Practice {.comp3270-source-slide .source-slide-heading .comp3270-native-slide data-source-slide=“astar-practice”}

A*-TSA Practice
69
32105141243Sh=7ah=9bh=4ch=2dh=5eh=3Gh=0

Start: S   ·   Goal: G

Use f(n)=g(n)+h(n)

Predict the expansion order
and returned path

Break ties by path-string order

Initial frontier: [(7, 'S')]
S @ 7 -> [(7, 'Sd'),
(10, 'SG'), (12, 'Sa')]
Sd @ 7 -> [(7, 'Sdb'), (9, 'Sde'),
(10, 'SG'), (12, 'Sa')]
Sdb @ 7 -> [(7, 'Sdbc'), (7, 'Sdbe'), (9, 'Sde'),
(10, 'SG'), (12, 'Sa')]
Sdbc @ 7 -> [(7, 'Sdbe'), (9, 'SdbcG'), (9, 'Sde'),
(10, 'SG'), (12, 'Sa')]
Sdbe @ 7 -> [(7, 'SdbeG'), (9, 'SdbcG'), (9, 'Sde'),
(10, 'SG'), (12, 'Sa')]
Solution path: (7, 'SdbeG')

Is A* Always Optimal?

Is A* Always Optimal?
70
Original Berkeley robot celebrating
It worked on Romania. Is that a guarantee?
Source: UC Berkeley CS188

Is A*-TSA Optimal? {.comp3270-source-slide .source-slide-heading .comp3270-native-slide data-source-slide=“astar-overestimate-question”}

Is A*-TSA Optimal?
71
135Sh=7ah=6Gh=0
Start: S   ·   Goal: G
Which path will A*-TSA return?
Initial frontier: [(7, 'S')]
S @ 7 -> [(5, 'SG'), (7, 'Sa')]
Solution path: (5, 'SG')
Returned: SG, cost 5
Cheaper path: SaG, cost 1 + 3 = 4
h(a) = 6 overestimates the
true remaining cost of 3

Admissibility of Heuristic

Admissibility of Heuristic
72

An optimistic estimate

0 ≤ h(n) ≤ h*(n)

h*(n) is the true cheapest remaining cost

h(n) may underestimate, but must not overestimate

At a goal

h(goal)=0

Admissibility of Heuristic

Admissibility of Heuristic
73
135Sh=7ah=6Gh=0

Is h admissible for this graph?

h(a) = 6 > h*(a) = 3

h(S) = 7 > h*(S) = 4

Keep the same edge costs

What values are allowed for h(a)?

What values are allowed for h(S)?

Admissibility: Check Every State

Admissibility: Check Every State
74
135Sh=0…4ah=0…3Gh=0

From a

h*(a)=3
Therefore 0 ≤ h(a) ≤ 3

From S

h*(S)=min(5, 1+3)=4
Therefore 0 ≤ h(S) ≤ 4

Optimality of A*

Optimality of A*
75
AB

Let

  • A be an optimal goal node
  • B be a suboptimal goal node
  • h be admissible

Claim

  • A will exit the frontier before B

Optimality of A*

Optimality of A*
76
ABn

Let n be an ancestor of A

Let B and n both be on the frontier

Claim: n exits the frontier before B

f(n) ≤ f(A)

Admissibility, with n on the optimal route to A

f(A) < f(B)

B is suboptimal and both goal heuristics are zero

Optimality of A*

Optimality of A*
77
AB

All ancestors of A exit the frontier before B

A exits the frontier before B

A*-TSA is optimal with admissible h

Is This Heuristic Admissible?

Is This Heuristic Admissible?
78
11123Sh = 2ah = 4bh = 1ch = 1Gh = 0

True remaining costs

h*(G) = 0, h*(c) = 3
h*(a) = 4, h*(b) = 5
h*(S) = 5

Compare with h

0 ≤ 0   ·   1 ≤ 3   ·   4 ≤ 4
1 ≤ 5   ·   2 ≤ 5

All estimates pass

Yes, this heuristic is admissible

Optimality of A*: TSA {.comp3270-source-slide .source-slide-heading .comp3270-native-slide data-source-slide=“astar-tsa-success”}

Optimality of A*: TSA
79
11123Sh=2ah=4bh=1ch=1Gh=0
Start: S   ·   Goal: G
Initial frontier: [(2, 'S')]
S @ 2 -> [(2, 'Sb'), (5, 'Sa')]
Sb @ 2 -> [(4, 'Sbc'), (5, 'Sa')]
Sbc @ 4 -> [(5, 'Sa'), (6, 'SbcG')]
Sa @ 5 -> [(3, 'Sac'), (6, 'SbcG')]
Sac @ 3 -> [(5, 'SacG'), (6, 'SbcG')]
Solution path: (5, 'SacG')
Optimal path: SacG, cost 5

Optimality of A*: GSA

Optimality of A*: GSA
80
11123Sh=2ah=4bh=1ch=1Gh=0
Our GSA never expands a state twice
Initial frontier: [(2, 'S')]
Explored: ∅
S @ 2 -> [(2, 'Sb'), (5, 'Sa')]
Explored: {S}
Sb @ 2 -> [(4, 'Sbc'), (5, 'Sa')]
Explored: {S, b}
Sbc @ 4 -> [(5, 'Sa'), (6, 'SbcG')]
Explored: {S, b, c}
Sa @ 5 -> [(3, 'Sac'), (6, 'SbcG')]
Explored: {S, b, c, a}
Skip Sac: c already explored
Solution path: (6, 'SbcG')
What went wrong?

Consistency of Heuristic

Consistency of Heuristic
81
acGh=4h=1h=013

Definition

For every arc a → c

h(a) − h(c) ≤ cost(a,c)

Equivalently

h(a) ≤ cost(a,c) + h(c)

Here: 4 ≤ 1 + 1 is false

Consequence of consistency

The f value along a path never decreases

Consistency Keeps f from Decreasing

Consistency Keeps f from Decreasing
82
Recall the cheaper path S → a → c
cost = 1 a c
g = 1   ·   h = 4
f = 1 + 4 = 5
g = 2   ·   h = 1
f = 2 + 1 = 3
g rises by 1   ·   h falls by 3   →   f falls by 2
Consistency: h cannot fall by more than the step costs
f(v) − f(u) = cost(u, v) − (h(u) − h(v)) ≥ 0
With consistent h, GSA first expands each state via a cheapest path
Closing the state cannot block a cheaper route later

Consistency of Heuristic

Consistency of Heuristic
83
11123Sh=2ah=4bh=1ch=1Gh=0

Is h consistent for this graph?

h(u) ≤ cost(u, v) + h(v)

S → a:   2 ≤ 1 + 4

S → b:   2 ≤ 1 + 1

a → c:   4 > 1 + 1

b → c:   1 ≤ 2 + 1

c → G:   1 ≤ 3 + 0

No: a → c violates consistency
Keep all edge costs fixed
How could we repair h?

Two Ways to Repair the Heuristic

Two Ways to Repair the Heuristic
84
11123Sh=2ah=4bh=1ch=1Gh=0

Lower h(a) from 4 to 2

a → c: 2 ≤ 1 + 1
S → a: 2 ≤ 1 + 2

Or raise h(c) from 1 to 3

a → c: 4 ≤ 1 + 3
c → G: 3 ≤ 3 + 0

Both repairs work

Other edges remain consistent
Both heuristics remain admissible

A*: Key Takeaways

A*: Key Takeaways
85

A*-TSA

Returns a cheapest solution when h is admissible

Our A*-GSA

Returns a cheapest solution when h is consistent

Will it find a solution?

Yes, if one exists, with finite branching
and every step cost ≥ ε > 0

Time and memory

Can still grow exponentially

Planning vs. Identification

Planning vs. Identification
87
Planning
SG
The path matters

Find a sequence of actions

Compare path costs and depths

Use heuristics and a frontier

Identification
The final arrangement matters

Find an assignment to variables

Example: assign a position to each queen

Local search can be faster for some problems

Example: 8-Queens

Example: 8-Queens
88
Q1Q2Q3Q4Q5Q6Q7Q8
Lower cost is better
Goal: zero attacking pairs
State

Eight queens on the board, one per column

Successors

Move one queen to another square
in the same column

Every such move gives a neighbour

Cost function

Count pairs of queens that attack each other

Same row or diagonal

Direct: Q6 and Q8

Indirect: Q2 and Q8, with Q6 between

Count Attacking Pairs

Count Attacking Pairs
89
What is the cost of this state?
Q4Q1Q5Q2Q6Q8Q3Q7

Count each pair once

Q1 with Q2, Q3, Q5+3

Q2 with Q3, Q4, Q6, Q8+4

Q3 with Q5, Q7+2

Q4 with Q5, Q6, Q7+3

Q5 with Q6, Q7+2

Q6 with Q7, Q8+2

Q7 with Q8+1

3 + 4 + 2 + 3 + 2 + 2 + 1 = 17

Count the Neighbours

Count the Neighbours
90
How many different one-queen moves are possible?
Q4Q1Q5Q2Q6Q8Q3Q7

One queen

7 other rows

Eight queens

8 × 7 = 56 neighbours

Evaluate the Neighbours

Evaluate the Neighbours
91
What would the cost be after each move?
181214131312141414161315121412161412181315121414151414Q413161316Q1141715Q514161617Q2161815Q615Q81814Q3151514Q7161414131712141218

Each number is the cost of the whole board
after moving that column’s queen

Example: move Q2 to the top row
The resulting board costs 12

The current board costs 17

Lowest of all 56 costs: 12

Several moves tie; choose one at random

Improve the Current State

Improve the Current State
92
Current state
Cost: 17
Cost: 12
Compare neighbouring states
Three of the 56 neighbours; each moves the highlighted queen
Cost: 16
Cost: 12
Choose this state
Cost: 14
Cost = attacking pairs · Lower is better
Replace the current state, then repeat
Very little memory · Often finds good solutions in large spaces

Hill Climbing: One Attempt

Hill Climbing: One Attempt
93

Steepest descent for a cost we want to minimise

  1. Start with a random state
  2. If cost = 0, return the solution
  3. Find the lowest-cost neighbour
    Break ties at random
  4. If its cost ≥ current cost, stop this attempt
  5. Otherwise replace the current state; return to step 2

Accept only strictly lower costs

When Improvement Stops

When Improvement Stops
94

Current cost: 2

Lowest neighbour cost: 2

No strictly better move

Stop, but not solved

An equal-cost move would be a sideways move

Try the Experiment

Does the Experiment Match?

Does the Experiment Match?
96

Five seeds × 10,000 independent attempts

Solved

14.07%

Mean moves if solved

4.08

Mean moves if stopped

3.06

7,035 solutions in 50,000 attempts

Success across the five seeds: 13.23%–14.42%

Close to AIMA’s approximate 14% success and 4 / 3 moves

One strict attempt, without sideways moves · Accepted moves only

Try a New Starting State

Try a New Starting State
97
Random restart: begin each attempt from a fresh random board

Attempt 1

Stopped: cost 1

Attempt 2

Stopped: cost 3

Attempt 3

Solved: cost 0

Task Preparation

Task Preparation
QR code for the COMP3270 Moodle course
Log in to Moodle → Click Ed
98

Task: BFS-GSA

Task: BFS-GSA
TASK
SOLUTION
Solution: BFS-GSA
99
4274715612613912416SABCDEFHIJG

Start at S, goal G
Frontier: Add alphabetically

1. Exploration Order

2. Solution path

Uppercase strings, no spaces
Example: SAG

QR code for the BFS-GSA Ed questionSubmit on Ed

Explored
SABCDEFJH

Solution
SAEG

Task: DFS-TSA

Task: DFS-TSA
TASK
SOLUTION
Solution: DFS-TSA
100
4274715612613912416SABCDEFHIJG

Start at S, goal G
Frontier: Add alphabetically

1. Exploration Order

2. Solution path

Uppercase strings, no spaces
Example: SAG

QR code for the DFS-TSA Ed questionSubmit on Ed

Explored
SCJFIH

Solution
SCFIHG

Task: UCS-GSA

Task: UCS-GSA
TASK
SOLUTION
Solution: UCS-GSA
101
4274715612613912416SABCDEFHIJG

Start at S, goal G
Frontier: Add alphabetically

1. Exploration Order

2. Solution path

Uppercase strings, no spaces
Example: SAG

QR code for the UCS-GSA Ed questionSubmit on Ed

Explored
SBADECFJHI

Solution
SBEHG
Cost: 14

Task: A*-GSA

Task: A*-GSA
TASK
SOLUTION
Solution: A*-GSA
102
4274715612613912416Sh=10Ah=10Bh=12Ch=7Dh=8Eh=6Fh=6Hh=4Ih=5Jh=8Gh=0
QR code for the A-star GSA Ed questionSubmit on Ed

Start at S, goal G
Frontier: Add alphabetically

1. Exploration Order

2. Solution path

3. Admissible?

4. Consistent?

Uppercase strings, no spaces
Example: SAG

Explored: SABEH

Solution: SBEHG
Cost: 14

Admissible: Yes
h(n)≤h*(n)h(n)\leq h^*(n)

Consistent: No
B→A:1<12−10B\to A:\;1<12-10
B→E:5<12−6B\to E:\;5<12-6

Constraint Satisfaction Problems

Constraint Satisfaction Problems
104

Constraint Satisfaction Problems

Constraint Satisfaction Problems
105

A factored state records a value for each variable

A solution assigns every variable a value that satisfies all constraints

Use constraints to rule out combinations before exploring them

Defining CSPs

Defining CSPs
106

VariablesX={X1,…,Xn}X=\{X_1,\ldots,X_n\}

DomainsDiD_i contains the allowed values of XiX_i

ConstraintsAllowable combinations of values

A state is a partial or complete assignment{Xi=vi,Xj=vj,…}\{X_i=v_i,\;X_j=v_j,\ldots\}

Solutions to CSPs

Solutions to CSPs
107

Consistent: no constraint is violated

Complete: every variable has a value

A solution is both consistent and complete

Australia: Map Colouring

Australia: Map Colouring
108

VariablesX={WA,NT,Q,NSW,V,SA,T}X=\{\mathrm{WA,NT,Q,NSW,V,SA,T}\}

DomainsDi={red,green,blue}D_i=\{\mathrm{red,green,blue}\}

ConstraintsNeighbours have different colours

Constraint Graph It can be helpful to visualize a CSP as a constraint graph Nodes correspond to variables Arcs show existence of constraints 99 Q NSW V NT WA SA

Constraint Graph
109

Nodes represent variables

Edges represent constraints

Tasmania is independent
of the mainland variables

Q

NSW

V

NT

WA

SA

T

Solving CSPs

Solving CSPs
110

StateThe values assigned so far

Initial StateEmpty assignment {}\{\}

SuccessorAssign a value to an unassigned variable

Goal TestComplete and consistent

DFS

DFS
112

…

…

…

Early mistake …

…

…

Backtracking 104 D = {red, green, blue} X = {WA, NT, Q, NSW, V, SA, T} . . .

Backtracking
114

. . .

Backtracking

Backtracking
115
Variables: {NSW,WA,NT,Q,SA,V,T}\{\mathrm{NSW},\mathrm{WA},\mathrm{NT},\mathrm{Q},\mathrm{SA},\mathrm{V},\mathrm{T}\}
Colors: {red,green,blue}\{\mathrm{red},\mathrm{green},\mathrm{blue}\}

Q

NSW

V

NT

WA

SA

T

NSW

WA

NT

NT

Q

Q

Q

SA

SA

SA

SA

Q

NT

Q

Q

SA

SA

SA

SA

Q

NT

Q

WA

NT

Q

Q

SA

SA

SA

V

V

T

Backtracking Search

Backtracking Search
116
Choose a variable → Try a consistent value → Recurse → Undo

Improving Backtracking

Improving Backtracking
117

Can we detect inevitable failure earlier?

Forward checking: remove conflicting values from neighbours

Constraint propagation: repeat these deductions with AC-3

Forward Checking

Forward Checking
118
After each assignment, remove conflicting values
from the domains of unassigned neighbours
WA NT Q NSW V SA T

Detect failure earlier

Backtracking with Forward Checking

Backtracking with Forward Checking
119
Variables: {NSW,WA,NT,Q,SA,V,T}\{\mathrm{NSW},\mathrm{WA},\mathrm{NT},\mathrm{Q},\mathrm{SA},\mathrm{V},\mathrm{T}\}
Colors: {red,green,blue}\{\mathrm{red},\mathrm{green},\mathrm{blue}\}

Q

NSW

V

NT

WA

SA

T

NSW

NSW

WA

NT

Q

NT

Q

Q

NT

Q

WA

NT

Q

SA

V

T

When Forward Checking Misses Failure

When Forward Checking Misses Failure
120
After each assignment, remove conflicting values
from the domains of unassigned neighbours
WA NT Q NSW V SA T
Doomed to
fail
Can we detect
this earlier?

Consistency of an Arc An arc X ⟶ Y is consistent iff for every x in the tail there is some y in the head which could be assigned without violating a constrain 1

Consistency of an Arc
121
An arc X→YX\to Y is consistent if every x∈DXx\in D_X has a compatible y∈DYy\in D_Y
WA NT Q NSW V SA T
∀x∈DX,∃y∈DY:CXY(x,y)\forall x\in D_X,\;\exists y\in D_Y:\;C_{XY}(x,y)

Link

Constraint Propagation

Constraint Propagation
122
When a domain shrinks, recheck arcs pointing into it
Repeat until no domain changes, or a domain is empty
X→YX\to Y: every value in DXD_X needs a compatible value in DYD_Y
WA NT Q NSW V SA T

AC-3

AC-3
123
Why exclude
the reverse arc?
Revise an arc → Revisit affected incoming arcs

Why Exclude the Reverse Arc?

Why Exclude the Reverse Arc?
124

XiX_i

XjX_j

Xk1X_{k_1}

Xk2X_{k_2}

Xk3X_{k_3}

Why don’t I have to add this one ?

Update the domain
of XiX_i

XiX_i has four neighbours
including XjX_j

=Xk4=X_{k_4}

Link

Backtracking with AC-3

Backtracking with AC-3
125
Variables: {NSW,WA,NT,Q,SA,V,T}\{\mathrm{NSW},\mathrm{WA},\mathrm{NT},\mathrm{Q},\mathrm{SA},\mathrm{V},\mathrm{T}\}
Colors: {red,green,blue}\{\mathrm{red},\mathrm{green},\mathrm{blue}\}

Q

NSW

V

NT

WA

SA

T

NSW

WA

NT

NT

WA

NT

NT

Q

SA

V

T

Variable and Value Ordering

Variable and Value Ordering
126

Variable Ordering

Minimum Remaining Values (MRV)

Choose the variable with the fewest legal values

Most constrained variable

Fail-first heuristic

Break MRV Ties

Degree Heuristic

Most constraints on unassigned variables

Value Ordering

Least Constraining Value (LCV)

Rules out the fewest values in unassigned neighbours

Variable Ordering (MRV + Deg) Degree Heuristic (Deg) Choose the variable with the most constraints on remaining variables 118 using forward checking D = {red, g

Variable Ordering (MRV + Deg)
128

Degree Heuristic

Among MRV ties, choose the variable with the most
constraints on unassigned variables

using forward checking

Value Ordering (LCV) Choose the value that rules out the fewest values in the remaining variables Least constraining value (LCV) 119 Suppose we have decided to

Value Ordering (LCV)
129

Least Constraining Value

Try the value that removes the fewest options
from unassigned neighbours

Assign Q Next
Which Colour First?

Backtracking with All Heuristics

Backtracking with All Heuristics
130
AC-3 · MRV · Degree · LCV
Variables: {NSW,WA,NT,Q,SA,V,T}\{\mathrm{NSW},\mathrm{WA},\mathrm{NT},\mathrm{Q},\mathrm{SA},\mathrm{V},\mathrm{T}\}
Colors: {red,green,blue}\{\mathrm{red},\mathrm{green},\mathrm{blue}\}

Q

NSW

V

NT

WA

SA

T

SA

NSW

WA

NT

Q

V

T

Other Agents Choose Their Own Moves

Other Agents Choose Their Own Moves
132

Our next state depends on our move and their response

Chess board
XOXO
Backgammon board

Chance: Later

Competing agents

Here: Two Players · Alternating Turns · Deterministic · Fully Observable

Zero-Sum: What Helps MAX Hurts MIN

Defining a Game

Defining a Game
133
State s; Initial State s₀
Board configuration and player to move
Player(s)
Whose turn is it?
Actions(s); Result(s, a)
Legal moves; state after a move
TerminalTest(s)
Has the game ended?
Utility(s, p)
Final payoff for player p

Game Tree: Nodes Are States; Edges Are Moves

Tic-Tac-Toe Game Tree

Tic-Tac-Toe Game Tree
134

Players

X is MAX
O is MIN

Utility for X

Win: +1
Draw: 0
Loss: −1

State Includes
the Player to Move

Think About Their Reply

Think About Their Reply
135
One agent reasons about its opponent, who reasons about its opponent

Back Up Values from the Leaves

Back Up Values from the Leaves
136
31224 MAXMINUTILITYAll ValuesScore MAX 3min(3, 12) = 3 2min(2, 4) = 2 3max(3, 2) = 3

MAX Chooses Left: 3 Is Larger Than 2

Minimax Follows the Tree Recursively

Minimax Follows the Tree Recursively
137
def minimax(tree, maximizing=True):
    if not isinstance(tree, list): return tree
    values = [minimax(child, not maximizing) for child in tree]
    return max(values) if maximizing else min(values)

Base Case
A leaf returns its utility

Recursive Step
Visit every child and switch the player

Back Up
MAX returns max; MIN returns min

One Recursive Call per State in the Game Tree

Run Minimax on a Deeper Tree

Run Minimax on a Deeper Tree
138

Minimax Practice

Minimax Practice
139

MIN Moves First: What Is the Root Value? Which Move?

MINMAXMINUTILITY3118555191010131183331

Value 1 · MIN Chooses the Middle Branch

Task: Minimax

Task: Minimax
Solution: Minimax
TASK
SOLUTION
140

Find the Values of x That Make Left Strictly Better

Use x on the left
No spaces
Example: x<3

QR code for the Minimax Ed taskSubmit on Ed
MAXMINMAXUTILITYx-811-25128-4

Left = min(max(x, −8), 11) · Right = 8

x > 8: Left Wins · x = 8: Tie

What Does Minimax Guarantee?

What Does Minimax Guarantee?
141

An Optimal Strategy Against Optimal Opposition

Opponent chooses moves in tic-tac-toeDifferent opponents may choose differently

It Maximizes the Worst-Case Payoff

It Does Not Predict Every Opponent’s Actual Move

What If MIN Makes Mistakes?

What If MIN Makes Mistakes?
142
MAXMINUTILITY1010109100910

Left Guarantees 10 · Right Guarantees 9

If MIN Chooses Randomly: Right Averages 54.5

Minimax Properties

Minimax Properties
143

Finite Game Tree · Branching Factor b · Maximum Depth m

Complete?
Yes, for a finite game tree
Optimal?
Yes, against optimal opposition
Time
O(bm)
Space
O(bm), with DFS and stored successor lists

Search All Replies, Depth First

Full Search Is Too Large

Full Search Is Too Large
144

Illustrative Chess Estimate

b ≈ 35 · m ≈ 100

35100 ≈ 2.6 × 10154

We Cannot Search to Every Terminal Position

Chess position

Resource Limits

Resource Limits
145
Agent can see only part of a large search landscape

Stop at a Depth Limit

Stop at a Depth Limit
146

Depth Limit ℓ = 2 · MAX and MIN Still Alternate

MAXMINEVAL????

Terminal: Exact Utility · Cutoff: Estimate the Position

Time: O(bℓ) · Space: O(bℓ)

Back Up the Cutoff Estimates

Back Up the Cutoff Estimates
147
MAXMINEVAL-1-2-24944

Estimated Root Value: 4 · Choose Right

The Guarantee Depends on the Estimates

Evaluate a Non-Terminal Position

Evaluate a Non-Terminal Position
148

Eval(s): Estimate the Position’s Value for MAX

Ideal: The True Minimax Value

Useful: Fast Enough to Evaluate Many Positions

A Larger Number Should Mean a Better Position for MAX

Agent evaluates the value of a position

Task: Evaluation Functions

Task: Evaluation Functions
Solution: Evaluation Functions
TASK
SOLUTION
149
LEFT POSITION
Left: Pacman at 1, food at 4, ghost at 8
RIGHT POSITION
Right: Pacman at 1, food at 3, ghost at 4

Which Functions Prefer the Left Position?

f=distance to food·g=distance to ghost

A.1f

B.g

C.g+1f

D.g+1000f

Left: f = 3, g = 7 · Right: f = 2, g = 3

B and C Prefer Left · A and D Prefer Right

Combine Features into an Evaluation

Combine Features into an Evaluation
150

Eval(s)=w1f1(s)+⋯+wnfn(s)

Pawn
1
Knight / Bishop
3
Rook
5
Queen
9
Chess board: material is only part of the evaluation

Feature: MAX’s Material − MIN’s Material

Also Consider King Safety and Pawn Structure

Material Is Not Enough

Material Is Not Enough
151

Who Has the Advantage in Each Position?

Two chess positions that differ only in the lower-right rook

(a) Material Count: Black Has More Material

(b) Tactical Check: White Can Capture the Queen

Material Alone Can Miss an Immediate Tactic

Depth and Evaluation Error

Depth and Evaluation Error
152

At the Cutoff, We Estimate a Non-Terminal State

A Deeper Cutoff Is Often Closer to the Real Outcome

Tradeoff: Better Features or More Search?

A shallow game treeA deeper game tree

The Horizon Effect

The Horizon Effect
153

A Bad Consequence Lies Just Beyond the Cutoff

A Delaying Move Pushes It Out of Sight

The Delay May Make the Final Outcome Worse

A search agent sees only a limited horizon

Can Black Save the Bishop?

Can Black Save the Bishop?
154
Chess horizon-effect example with Black to move

Black to Move

Can a Delaying Tactic Avoid the Loss?

No · It Only Pushes the Loss Beyond a Shallow Horizon

Can We Skip Part of the Tree?

Can We Skip Part of the Tree?
155

Can We Compute the Exact Minimax Choice Without Visiting Every Node?

A game tree with some branches omitted

Yes · When a Branch Cannot Affect the Decision

A Branch Cannot Beat the Current Best

A Branch Cannot Beat the Current Best
156
31282××3≤ 2≥ 3 MAXMINUTILITY

Left Gives 3 · Right MIN Finds 2

The Other Right Leaves Cannot Change MAX’s Choice

Alpha–Beta Pruning

Alpha–Beta Pruning
157

Skip Branches That Cannot Change the Root Decision

Result
Same minimax value and optimal root action
Benefit
Often visits far fewer nodes
Requirement
Track bounds while searching left to right

Pruning Changes Work, Not the Answer

MIN Pruning

MIN Pruning
158
≥ α α UNSEEN ≤ v vpq v ≤ α → PRUNE

MIN Pruning at Greater Depth

MIN Pruning at Greater Depth
159
≥ α α … v UNSEEN≤ v α: MAX's best explored optionon the path from the current node to the root v ≤ α → PRUNE

MIN Pruning at Greater Depth

MIN Pruning at Greater Depth
160
α = 3 3 7α = 7 6UNSEEN≤ v α: MAX's best explored optionon the path from the current node to the root v ≤ α → PRUNE

MIN Pruning at Greater Depth

MIN Pruning at Greater Depth
161
α = 7 7 3α stays 7 6UNSEEN≤ v α: MAX's best explored optionon the path from the current node to the root v ≤ α → PRUNE

Pruning Conditions

Pruning Conditions
162
α: MAX's best explored option α ≤ v vUNSEEN v ≤ α → PRUNE β: MIN's best explored option β ≥ v vUNSEEN v ≥ β → PRUNE MAX: α ← max(α, v)α starts at −∞ and risesMIN: β ← min(β, v)β starts at +∞ and falls

Which Values Can Change the Choice?

Which Values Can Change the Choice?
163
68 v α = 6 β = 8Current subtree inherits α = 6 and β = 8 45678910v ≤ 6: root returns 66 < v < 8: root returns vv ≥ 8: root returns 8

MIN Pruning

MIN Pruning
164
68 ??? α = 6β = 8 68lower bound < β: keep searchinglower bound ≥ β: prune v ≥ 7v ≥ 77 9v ≥ 9 > β = 8v ≥ 9

Initial Bounds

Initial Bounds
165
UTILITY467512848193

Root α = −∞ · Current β = +∞

First MAX Returns 6

First MAX Returns 6
166
UTILITY4675128481936

Left MIN updates β to 6

Left MIN Sets Alpha to 6

Left MIN Sets Alpha to 6
167
UTILITY467×128481936≥ 76α = 6

Root updates α to 6

Middle MAX Returns 2

Middle MAX Returns 2
168
UTILITY467×128481936≥ 76α = 62

Middle MIN updates β to 2

Middle MIN Reaches the Cutoff

Middle MIN Reaches the Cutoff
169
UTILITY467×128481936≥ 76α = 62≤ 2

β = 2 ≤ α = 6

Middle Branch Pruned

Middle Branch Pruned
170
UTILITY467×12××81936≥ 76α = 62≤ 2

β = 2 ≤ α = 6

Right MAX Returns 8

Right MAX Returns 8
171
UTILITY467×12××81936≥ 76α = 62≤ 28

Right MIN updates β to 8

Next MAX Sees 9

Next MAX Sees 9
172
UTILITY467×12××81936≥ 76α = 62≤ 28≥ 9

Current v = 9 · Right MIN β = 8

Right MAX Reaches the Cutoff

Right MAX Reaches the Cutoff
173
UTILITY467×12××81936≥ 76α = 62≤ 28≥ 9

v = 9 ≥ β = 8

Right MIN Returns 8

Right MIN Returns 8
174
UTILITY467×12××819×6≥ 76α = 62≤ 28≥ 98

Root α = 6 · Right value = 8

Root Chooses 8

Root Chooses 8
175
UTILITY467×12××819×6≥ 762≤ 28≥ 988

Final α = 8

Alpha–Beta Search in Python

Alpha–Beta Search in Python
176

Task: Alpha–Beta Pruning

Task: Alpha–Beta Pruning
Solution: Alpha–Beta Pruning
TASK
SOLUTION
177

Search Left to Right · Which Branch Is Pruned?

UTILITY108450ABCDEFF

Pruned Branch: F · Left MIN Gives 8, Then Right MIN Finds 4 ≤ α

Task: Deeper Alpha–Beta Pruning

Task: Deeper Alpha–Beta Pruning
Solution: Deeper Alpha–Beta Pruning
TASK
SOLUTION
178

Search Left to Right · Which Branches Are Pruned?

UTILITY10699812204ABCDEFGHIJKLMNFJMN

Pruned Branches: F, J, M, N

A Bound Is Not an Exact Value

A Bound Is Not an Exact Value
179
A B 10 10 ? 10 Exact Value α = 10 v ≤ 10 β = 10 ≤ α = 10: Prune Pruned 0 10 Actual Value of B: min(10, 0) = 0
Search Left to Right · Which Move Should MAX Keep?
A Returns 10 · Keep A and Set α = 10
B Returns 10 as a Bound · This Does Not Prove a Tie
Keep A · Replace the Best Move Only on a Strict Improvement

Move Ordering Controls Pruning

Move Ordering Controls Pruning
180
31282××324631283GOOD ORDERPOOR ORDER· 4 LEAVES· 6 LEAVES

Same Minimax Value: 3 · Different Amount of Search

Good Ordering Searches Much Less

Good Ordering Searches Much Less
181

Minimax: O(bm)

Ideal Alpha–Beta Ordering: O(bm/2)

Roughly Twice the Search Depth for the Same Node Budget

Example: b = 10 and m = 6 Gives 10⁶ Leaves vs About 10³

Worst Case Remains O(bm)

Knuth & Moore (1975), An Analysis of Alpha-Beta Pruning

Worst Case Uses MIN’s Choice

Worst Case Uses MIN’s Choice
182
10109100 10min(10, 10) = 10 9min(9, 100) = 9 10 UTILITY

MAX Chooses Left: 10 > 9

Chance Uses the Expected Value

Chance Uses the Expected Value
183
101091000.50.50.50.5 100.5(10) + 0.5(10) = 10 54.50.5(9) + 0.5(100) = 54.5 54.5 CHANCEUTILITY

MAX Chooses Right: 54.5 > 10

Why Chance Nodes Appear

Why Chance Nodes Appear
184
Explicit randomness
Dice, shuffled cards, noisy outcomes
Agent model
An opponent policy represented by probabilities
Action failure
The intended action may not occur

A Chance Node Needs a Probability Model

Expected Value Is Only as Good as That Model

Expectimax Example

Expectimax Example
186
23140.90.10.90.1 2.11.32.1 CHANCEUTILITY

0.9(2) + 0.1(3) = 2.1

0.9(1) + 0.1(4) = 1.3

MAX Chooses Left: 2.1 > 1.3

Task: Minimax or Expectimax?

Task: Minimax or Expectimax?
187
TASK

Pacman First: WEST or EAST

After WEST and Both Ghosts, Pacman: EAST or SOUTH

Lower Ghost: NORTH or EAST · Upper Ghost: WEST only

Minimax: Worst Legal Ghost Move

Expectimax: Lower Ghost N/E with Probability 0.5 Each

Only Food Eaten: Win · Ghost Collision: Loss

Score: −1 per Pacman action · +10 food · +500 win · −500 loss

Collision on Food: Loss, No Food Points

1. Under minimax, what is Pacman’s optimal first action?

2. What value does minimax assign to the root?

3. Under expectimax, what is Pacman’s optimal first action?

4. What value does expectimax assign to the root?

Solution: Pacman Game Tree

Solution: Pacman Game Tree
188
SOLUTION
WESTEASTNORTHEASTWESTWESTEASTSOUTHEASTSOUTHLOSS−500 − 2 = −502LOSS−500 − 2 = −502LOSS−500 − 2 = −502WIN500 + 10 − 2 = 508LOSS−500 − 1 = −501

Solution: Minimax

Solution: Minimax
189
SOLUTION
WESTEASTNORTHEASTWESTWESTEASTSOUTHEASTSOUTHLOSS−500 − 2 = −502LOSS−500 − 2 = −502LOSS−500 − 2 = −502WIN500 + 10 − 2 = 508LOSS−500 − 1 = −501MAX: −502MAX: 508−502508−502min(−502, 508) = −502−501Minimax chooses EAST: −501 > −502

Solution: Expectimax

Solution: Expectimax
190
SOLUTION
WESTEASTNORTH · ½EAST · ½WESTWESTEASTSOUTHEASTSOUTHLOSS−500 − 2 = −502LOSS−500 − 2 = −502LOSS−500 − 2 = −502WIN500 + 10 − 2 = 508LOSS−500 − 1 = −501MAX: −502MAX: 508−5025083½(−502) + ½(508) = 33Expectimax chooses WEST: 3 > −501

More Than Two Agents

More Than Two Agents
191
Three agents play a game together

Utility Vectors

Utility Vectors
192

Red chooses the first value · Green the second · Blue the third

(1, 6, 6)(7, 1, 2)(6, 1, 2)(7, 2, 1)(5, 1, 7)(1, 5, 2)(7, 7, 1)(5, 2, 5)(1, 6, 6)(6, 1, 2)(5, 1, 7)(5, 2, 5)(1, 6, 6)(5, 2, 5)(5, 2, 5)

Reading

Reading
193
AIMA Chapter 3
AIMA Chapter 4
Search in Complex Environments · 62 pageshttps://comp3270.dirk.hk/AIMA_Chapter_4.pdf
AIMA Chapter 5
Adversarial Search · 63 pageshttps://comp3270.dirk.hk/AIMA_Chapter_5.pdf
AIMA Chapter 6
Constraint Satisfaction · 50 pageshttps://comp3270.dirk.hk/AIMA_Chapter_6.pdf

Password: Dirk