Introduction to AI
🧠 Introduction to Artificial Intelligence with Python — Search Algorithms
1️⃣ Search Problems
Anytime a computer appears intelligent—recognizing faces, playing games, understanding language—it is often powered by search algorithms. The core idea: an AI needs to find a sequence of actions to reach a goal from an initial state.
Key Terminology
Agent: An entity that perceives its environment and acts upon it. Example: a car navigation system.
State: A configuration of the agent and its environment at a given moment. In a sliding-tile puzzle, each arrangement of tiles is a distinct state.
Initial state: The state where the agent begins.
Actions: Choices available in a given state. Formally, a function
actions(s)returns the set of all actions executable in states. Actions are state-dependent (e.g., you can only slide a tile into an empty space).Transition model: Describes the result of applying an action to a state. Formally,
result(s, a)returns the state that follows after performing actionain states.State space: The set of all states reachable from the initial state via any sequence of actions. Often visualized as a graph where nodes are states and edges are actions.
Goal test: A function that determines whether a given state is a goal state. Some problems have one goal, others multiple.
Path cost: A numerical cost assigned to each action (or sequence of actions). The goal is often to find a solution with the lowest path cost.
Solution: A sequence of actions from the initial state to a goal state.
Optimal solution: A solution with the lowest path cost among all possible solutions.
Definition: A search problem is defined by an initial state, a set of actions (with a transition model), a goal test, and a path cost function. The objective is to find an optimal solution.
2️⃣ Solving a Search Problem
Data Structure: Node
A node is a data structure that packages information about a state during search. It typically stores:
State: the current configuration
Parent: the node that led to this state (used for backtracking)
Action: the action taken from the parent to reach this state
Path cost: the cumulative cost from the initial state to this node
The Frontier
The frontier is a data structure that contains all nodes that have been discovered but not yet explored. The search algorithm repeatedly picks a node from the frontier, checks if it is a goal, and if not, expands it (adds its neighbors to the frontier).
Basic Search Algorithm (without cycle prevention)
Start with frontier containing the initial state.
Loop:
If frontier is empty → no solution.
Remove a node from frontier.
If node contains goal state → return solution.
Otherwise, expand the node: add all resulting nodes to frontier.
Problem: Infinite Loops
If the graph has cycles (e.g., bidirectional edges), the algorithm may revisit states endlessly. Solution: maintain an explored set (or "closed set") of states already visited.
Revised Algorithm (with explored set)
Start with frontier containing initial state. Start with empty explored set.
Loop:
If frontier is empty → no solution.
Remove a node from frontier.
If node contains goal → return solution.
Add node's state to explored set.
Expand node: for each resulting node, if its state is not in frontier and not in explored set, add it to frontier.
This ensures each state is considered at most once.
3️⃣ Uninformed Search
Uninformed search algorithms use no problem-specific knowledge beyond the problem definition. They treat all states equally.
Depth-First Search (DFS)
Data structure: stack (Last-In, First-Out)
Behavior: Always expands the deepest node in the frontier. Goes along one path until a dead end, then backtracks.
Properties:
Will find a solution if one exists (in finite state spaces).
Not guaranteed to find the optimal solution (may find a longer path).
Memory efficient: only needs to store one branch of the search tree.
Visual intuition: In a maze, DFS picks one direction and follows it all the way to the end; if it hits a wall, it returns to the last junction and tries another direction.
Breadth-First Search (BFS)
Data structure: queue (First-In, First-Out)
Behavior: Always expands the shallowest node in the frontier.
Properties:
Finds the optimal solution if all actions have the same cost (finds the path with fewest steps).
Explores all nodes at distance
kbefore any node at distancek+1.Memory intensive: must store all nodes at the current depth and deeper, which can be huge.
Visual intuition: In a maze, BFS explores all cells one step away, then two steps away, etc., radiating outward like a wave.
Trade-offs
Aspect | DFS | BFS |
|---|---|---|
Optimality | Not guaranteed | Guaranteed (if cost per step is constant) |
Memory | Low (only current path) | High (entire frontier) |
Completeness | Yes (finite graphs) | Yes (finite graphs) |
Typical behavior | Explores deep paths first | Explores shallow paths first |
4️⃣ Informed Search
Informed search uses problem-specific knowledge (a heuristic) to guide the search toward the goal more efficiently.
Heuristic Function h(n)
A heuristic function estimates the cost from a given state n to the goal. It is an informed guess, not guaranteed to be exact. Example for a grid maze: Manhattan distance (sum of horizontal and vertical steps, ignoring walls).
Definition: A heuristic is admissible if it never overestimates the true cost to the goal. It is consistent if for every node
nand its successorn'(with costc),h(n) ≤ h(n') + c.
Greedy Best-First Search (GBFS)
Strategy: Always expand the node with the smallest
h(n)(the one estimated closest to the goal).Data structure: priority queue ordered by
h(n).Properties:
Can be much faster than BFS if heuristic is good.
Not optimal: may take a longer path if a locally promising heuristic leads away from the true optimal path.
Example maze: At a fork, GBFS chooses the cell with smaller Manhattan distance to the goal, potentially going into a dead end if the heuristic is misleading.
A* Search
Strategy: Expand the node with the smallest
f(n) = g(n) + h(n), where:g(n)= cost so far to reach nodenh(n)= heuristic estimate fromnto goal
Data structure: priority queue ordered by
f(n).Properties:
Optimal if
h(n)is admissible (and consistent for graph search).Considers both the cost incurred and the estimated remaining cost; avoids the "greedy" trap by preferring states that are cheap to reach even if the heuristic is slightly larger.
Example revisited: A* chooses a path that may have a larger
h(n)but smallerg(n), leading to the true optimal route.
Heuristic Quality
A better heuristic (closer to true remaining cost, while still admissible) reduces the number of states explored. Designing good heuristics is a key challenge in AI search problems.
5️⃣ Adversarial Search
In adversarial situations (e.g., two-player games), an AI must reason about an opponent trying to thwart its goals. The classic algorithm is Minimax.
Game Formulation
Initial state
S0: starting board (e.g., empty tic-tac-toe grid)Player function
player(s): returns whose turn it is (X or O)Actions
actions(s): set of legal moves in statesTransition model
result(s, a): the state after taking actionain statesTerminal test
terminal(s): checks if the game is overUtility function
utility(s): numeric value of a terminal state (e.g., 1 for X win, -1 for O win, 0 for draw)
Minimax Algorithm
Two players:
Maximizer (X) wants to maximize the final score.
Minimizer (O) wants to minimize the final score.
The algorithm recursively computes the value of a state:
If terminal, return its utility.
If it's the maximizer's turn, the value is the maximum of the values of all successor states.
If it's the minimizer's turn, the value is the minimum of the values of all successor states.
Pseudocode:
function maxValue(state):
if terminal(state): return utility(state)
v = -∞
for action in actions(state):
v = max(v, minValue(result(state, action)))
return v
function minValue(state):
if terminal(state): return utility(state)
v = +∞
for action in actions(state):
v = min(v, maxValue(result(state, action)))
return vThe optimal action for a player is the one that leads to the successor with the best value for that player.
Example: Tic-Tac-Toe Decision
Given a board with O to move and two open squares, Minimax evaluates both options:
If O moves in upper left → X gets three in a row (value 1)
If O moves in bottom middle → X moves, game ends in draw (value 0)
O, as minimizer, chooses the move leading to value 0 (the draw) over value 1 (loss).
Optimization: Alpha-Beta Pruning
Alpha-beta pruning eliminates branches that cannot influence the final decision. It tracks two values:
Alpha: the best (highest) value the maximizer can guarantee so far.
Beta: the best (lowest) value the minimizer can guarantee so far.
If at any point alpha ≥ beta, further exploration of that branch is pointless (pruning). This can drastically reduce the search tree without affecting the result.
Depth-Limited Minimax
For complex games like chess, searching to the end of the game is impossible (exponential explosion). Instead, depth-limited Minimax limits the search depth and uses an evaluation function to estimate the utility of non-terminal states.
Evaluation function: typically a weighted sum of features (e.g., material advantage, piece mobility, king safety) that estimates the likelihood of winning.
Quality of play depends heavily on the evaluation function's accuracy.
📌 Key Takeaways
Search problems underpin many AI tasks: pathfinding, puzzle solving, game playing.
DFS and BFS are uninformed; DFS uses less memory but is not optimal, BFS finds shortest paths but uses more memory.
Greedy Best-First Search uses heuristics to speed up search but may be suboptimal.
A* combines heuristic and actual cost; optimal if heuristic is admissible and consistent.
Minimax provides optimal play in deterministic two-player games; alpha-beta pruning improves efficiency.
Depth-limited Minimax with evaluation functions handles huge game trees (e.g., chess).
The choice of heuristic or evaluation function critically affects performance and solution quality.

Ask anything
We've read this whole study set, so questions about it get the best answers.