Home Module 1 - Introduction to AI Module 2 - Problem-Solving & Search Module 3 - Uncertainty in AI Module 4 - Games & CSP Module 5 - AI in Practice & Ethics Important Questions
Module 1 of 5

Introduction to AI

This module lays the conceptual foundation of artificial intelligence: what it is, where it came from, how we classify it, and how we formally model an AI system as an agent embedded in an environment. We close the module with the first family of problem-solving algorithms - the uninformed (blind) search strategies: BFS, DFS, and UCS - which every later algorithm in this course (heuristic search, game-tree search, CSP search) extends or specializes.

11 Hours
9 Core Topics
CO1 - Analyze classical techniques (L4)
1.1

Definition and Scope of Artificial Intelligence

πŸ“˜ Definition

Artificial Intelligence (AI) is the branch of computer science concerned with building agents - systems - that perceive their environment through sensors and act upon it through actuators to achieve goals, exhibiting behavior that, if performed by a human, would be considered to require intelligence.

The word "intelligence" itself resists a single precise definition, which is why textbooks define AI along two independent axes: whether the system's internal process tries to mimic human thought or instead aims purely at rational behavior, and whether we judge it by its internal reasoning or by its external actions. Crossing these two axes produces four classical schools of thought.

The Four Views of AI (Russell & Norvig framework)

ViewFocusDefinitionExample research direction
Thinking HumanlyInternal process, human-likeSystems that think the way humans think (cognitive modeling)Cognitive science, neural modeling of reasoning
Thinking RationallyInternal process, logic-basedSystems that follow the "laws of thought" - formal logicLogic programming, automated theorem proving
Acting HumanlyExternal behavior, human-likeSystems that act so as to fool a human observer (Turing Test)Natural language processing, chatbots
Acting RationallyExternal behavior, goal-basedSystems that act to achieve the best expected outcome - the rational agent approachModern AI: search, planning, RL, ML

Modern AI courses - including this one - adopt the "acting rationally" view as the unifying definition, because it is mathematically precise (it can be expressed as maximizing an objective/utility function) and does not require us to first solve the philosophical problem of what human thought "really is."

Scope of Artificial Intelligence

AI is not one technique - it is an umbrella spanning multiple sub-fields, each tackling a different aspect of intelligent behavior:

  • Search & Planning - finding a sequence of actions from a start state to a goal state (Module 1 & 2 of this course).
  • Knowledge Representation & Reasoning - encoding facts about the world so a machine can draw new conclusions (propositional/predicate logic, covered in lab experiments 9–10).
  • Machine Learning - improving performance from data and experience rather than hand-coded rules (decision trees, covered in lab experiment 11).
  • Uncertainty & Probabilistic Reasoning - reasoning when information is incomplete or noisy (Bayesian networks, MDPs - Module 3).
  • Game Playing & Multi-agent Systems - decision-making when other intelligent agents are involved (Module 4).
  • Natural Language Processing, Computer Vision, Robotics - perception and communication sub-fields (mentioned for scope, not covered as a separate module here).
  • AI Ethics & Applications - responsible deployment in finance, healthcare, law enforcement (Module 5).
πŸ’‘ Real-world example

A food-delivery app's route optimizer is "acting rationally": it doesn't try to think like a human driver, it simply computes the path that minimizes expected delivery time given traffic data - exactly the rational-agent definition of AI in action.

βœ“ Why "Acting Rationally" Is Preferred
  • Mathematically well-defined via a utility/objective function
  • More general than imitating humans - humans aren't always rational
  • Maps directly onto engineering disciplines (control theory, optimization, economics)
βœ— Limitations of This View
  • Perfect rationality is computationally intractable in complex environments
  • Defining the "correct" utility function is itself a hard, value-laden problem
  • Doesn't capture consciousness or subjective experience (not AI's current goal anyway)
πŸ”‘ Key Points to Remember
  • AI has 4 classical definitions along 2 axes: thought vs behavior, human-like vs rational.
  • This course follows the rational agent paradigm.
  • AI's scope spans search, knowledge representation, learning, uncertainty, games, and ethics.

Quick Interview Questions

Q. Why do textbooks give four different definitions of AI instead of one?

Because "intelligence" can be judged from two independent perspectives - the internal reasoning process versus the external behavior - and each can be benchmarked either against human performance or against an ideal rational standard. Crossing these gives four non-equivalent definitions, each useful for different research goals.

Q. Which definition of AI does the rational-agent approach correspond to, and why is it preferred in engineering?

It corresponds to "Acting Rationally." It's preferred because it is mathematically precise - rationality is defined as maximizing expected performance measure/utility - which allows engineers to design, optimize, and formally verify agents rather than relying on vague notions of human-likeness.

1.2

Historical Overview and Evolution of AI

AI's history is a story of recurring waves of optimism followed by funding droughts known as "AI winters." Understanding this timeline helps explain why modern AI (rational agents, statistical learning) looks so different from 1960s AI (pure symbolic logic).

1943–1955 - Gestation
McCulloch–Pitts neuron; Turing's "Computing Machinery and Intelligence" (1950)
↓
1956 - Birth of AI
Dartmouth Conference - John McCarthy coins the term "Artificial Intelligence"
↓
1956–1974 - Early Enthusiasm
General Problem Solver, Logic Theorist, early NLP (ELIZA)
↓
1974–1980 - First AI Winter
Funding cuts after the Lighthill Report; combinatorial explosion exposed
↓
1980–1987 - Expert Systems Boom
MYCIN, XCON / DENDRAL; knowledge-based systems commercialized
↓
1987–1993 - Second AI Winter
Expert systems proved brittle and expensive to maintain
↓
1993–2011 - AI Becomes a Science
Probabilistic reasoning, Bayesian networks, Deep Blue beats Kasparov (1997)
↓
2011–Present - Deep Learning Era
Big data + GPUs; AlphaGo (2016), Transformers, large language models

Fig 1.1 - Timeline of AI's evolution through enthusiasm cycles and "winters"

Detailed Milestones Table

YearMilestoneSignificance
1950Alan Turing publishes "Computing Machinery and Intelligence"Proposes the Turing Test as an operational test for machine intelligence
1956Dartmouth Summer Research ProjectAI formally founded as an academic discipline; the term "AI" is coined
1958John McCarthy invents LISPFirst AI-oriented programming language, dominant for decades
1965ELIZA chatbot (Joseph Weizenbaum)Early demonstration of natural-language pattern matching
1972PROLOG developedLogic-programming language central to symbolic AI (used in this course's labs)
1980XCON expert system deployed by DECFirst major commercial success of rule-based expert systems
1997IBM Deep Blue defeats Garry KasparovFirst time a computer beats a reigning world chess champion - driven by Minimax + Alpha-Beta + massive search (Module 4)
2011IBM Watson wins Jeopardy!Demonstrates large-scale NLP + knowledge retrieval
2012AlexNet wins ImageNetSparks the deep learning revolution in computer vision
2016AlphaGo defeats Lee Sedol at GoCombines Monte Carlo Tree Search (Module 4) with deep neural networks
2020sLarge Language ModelsFoundation models trained on internet-scale text; basis of modern conversational AI
⚠ Why the "AI Winters" Happened

Both winters share a common root cause: overpromising relative to the compute and data available at the time. Early researchers underestimated the combinatorial explosion in search spaces and the brittleness of hand-coded rules - exactly the problems that heuristic search (Module 2) and probabilistic methods (Module 3) were later developed to solve.

πŸ”‘ Key Points to Remember
  • AI was formally founded at the 1956 Dartmouth Conference.
  • Two major "AI winters" occurred: 1974–80 and 1987–93.
  • Modern AI's resurgence (post-2011) is driven by big data, GPU compute, and deep learning.
  • Game-playing milestones (Deep Blue, AlphaGo) are landmark proofs-of-concept for the search algorithms taught in this course.
Q. What caused the first AI winter (1974–1980)?

Early AI systems hit the combinatorial explosion problem: search spaces grew exponentially and available hardware could not cope. The UK government's Lighthill Report (1973) was sharply critical of AI's progress, leading to major funding cuts in Britain and the US.

Q. What is the historical significance of the Dartmouth Conference?

Held in 1956 and organized by John McCarthy, Marvin Minsky, Nathaniel Rochester, and Claude Shannon, it is considered the founding event of AI as an academic field - the term "Artificial Intelligence" itself was coined by McCarthy for this workshop's proposal.

1.3

Types of AI: Narrow vs. General Intelligence

AI systems are commonly classified by the breadth of tasks they can competently perform. This classification is independent of how "smart" a system looks - a chess engine that crushes grandmasters is still classified as narrow because it cannot do anything besides play chess.

πŸ“˜ Definition - Narrow AI (Weak AI / ANI)

Artificial Narrow Intelligence (ANI) refers to AI systems designed and trained for a single task or a narrow set of related tasks. They operate within pre-defined boundaries and cannot transfer their competence to unrelated domains.

πŸ“˜ Definition - General AI (Strong AI / AGI)

Artificial General Intelligence (AGI) refers to a hypothetical AI system with the ability to understand, learn, and apply knowledge across any intellectual task a human can - i.e., possessing human-level, domain-independent cognitive flexibility. No AGI system exists today; it remains a research goal.

Comparison Table

AspectNarrow AI (ANI)General AI (AGI)
ScopeSingle task / domainAny cognitive task
AdaptabilityCannot transfer learning to new domainsTransfers knowledge across domains, like humans
Current statusExists widely todayTheoretical / not yet achieved
ExamplesSpam filters, recommendation engines, Siri/Alexa, AlphaGo, self-driving perception stacks, chess enginesNone deployed; depicted in fiction (HAL 9000, Skynet)
Underlying techniqueTask-specific ML models, search algorithms, rule systemsOpen research problem - possibly requires new paradigms
Risk profileBounded, task-specific failure modesHypothesized existential/alignment risk (actively debated)

A third, often-mentioned category for completeness:

πŸ“˜ Artificial Super Intelligence (ASI)

A hypothetical future stage where AI surpasses human intelligence across all domains, including creativity and social intelligence. Purely speculative at present - mentioned in AI ethics discussions (see Module 5) but has no working examples.

πŸ’‘ Real-world example

Google Translate is excellent at translation (narrow), but cannot play chess, diagnose disease, or hold a general conversation about unrelated topics - it has zero competence outside its trained task, illustrating the boundary of narrow AI.

βœ“ Advantages of Narrow AI
  • Highly optimized and reliable within its domain
  • Computationally efficient - doesn't waste resources on generality
  • Easier to test, certify, and deploy safely
βœ— Limitations of Narrow AI
  • Brittle outside its trained distribution (no common-sense fallback)
  • Requires a fresh model/system for every new task
  • Cannot reason about tasks it wasn't explicitly designed/trained for

Key Points to Remember

  • Almost all AI in production today is Narrow AI - this is a frequently tested exam fact.
  • AGI is a research aspiration, not a deployed technology.
  • Classification is by breadth of competence, not by performance level.
Q. Is AlphaGo an example of General AI? Justify.

No. AlphaGo is Narrow AI - despite superhuman performance at Go, it cannot perform unrelated tasks like language translation or medical diagnosis. Breadth of competence, not skill level, determines the Narrow vs General classification.

1.4

Agents and Environments

πŸ“˜ Definition - Agent

An agent is anything that can be viewed as perceiving its environment through sensors and acting upon that environment through actuators. Formally, an agent's behavior is described by the agent function, mapping any given percept sequence to an action.

ENVIRONMENT
↕ percepts / actions
SENSORS β†’ AGENT PROGRAM β†’ ACTUATORS

Fig 1.2 - The Agent–Environment interaction loop

Core Vocabulary (frequently tested)

TermMeaning
PerceptThe agent's perceptual input at any given instant
Percept sequenceThe complete history of everything the agent has perceived so far
Agent functionAn abstract mathematical mapping from percept sequences to actions
Agent programThe concrete implementation of the agent function, running on physical hardware (the "architecture")
Performance measureThe criterion used to judge how successful the agent's behavior is

Example: Vacuum-Cleaner World (also Lab Experiment 2)

A classic teaching example: a vacuum agent lives in a world of two locations (A and B), each either Clean or Dirty. Its percepts are [location, status]; its actions are {Left, Right, Suck, NoOp}.

A - Dirty
B - Clean

Fig 1.3 - Vacuum world: agent starts in A, perceives "Dirty", action = Suck

Percept SequenceRational Action
[A, Clean]Right
[A, Dirty]Suck
[B, Clean]Left
[B, Dirty]Suck

Types of Agent Architectures

  • Simple reflex agents - act only on the current percept using condition-action rules; no memory of history.
  • Model-based reflex agents - maintain an internal state/model of the unobserved parts of the world.
  • Goal-based agents - choose actions that achieve an explicit goal, often requiring search/planning (this is where Module 1–2's search algorithms plug in).
  • Utility-based agents - choose actions that maximize an expected utility function, allowing trade-offs between competing goals (links to Module 3's decision theory).
  • Learning agents - improve their performance element over time using a learning element and a critic that evaluates outcomes against the performance measure.

Environment Types (PEAS & Properties)

Before designing an agent, we describe its task environment using the PEAS framework: Performance measure, Environment, Actuators, Sensors.

PropertyMeaningExample
Fully vs. Partially ObservableCan sensors see the complete state at every instant?Chess (full) vs. Poker (partial)
Deterministic vs. StochasticDoes the next state depend only on current state + action?Chess (deterministic) vs. dice games (stochastic)
Episodic vs. SequentialAre experiences divided into independent episodes?Image classification (episodic) vs. chess (sequential)
Static vs. DynamicCan the environment change while the agent deliberates?Crossword (static) vs. self-driving (dynamic)
Discrete vs. ContinuousFinite distinct states/actions or continuous range?Chess (discrete) vs. robot navigation (continuous)
Single vs. Multi-agentDoes the agent act alone or alongside other agents?Crossword (single) vs. chess (multi/adversarial - Module 4)
πŸ’‘ Real-world example - PEAS for a self-driving car

Performance: safety, speed, legality, comfort. Environment: roads, traffic, pedestrians, signals. Actuators: steering, accelerator, brake, horn. Sensors: cameras, LIDAR, GPS, speedometer.

πŸ”‘ Key Points
  • Agent = sensors + actuators + agent program operating in an environment.
  • Five architectures: simple reflex, model-based reflex, goal-based, utility-based, learning.
  • Environments are described using PEAS and classified along 6 binary properties.

Interview Questions

Q. Differentiate between agent function and agent program.

The agent function is an abstract mathematical specification - possibly an infinite lookup table - describing what action to take for every possible percept sequence. The agent program is the actual, concrete software/hardware implementation that runs on the agent's architecture and realizes that function in practice.

Q. Why is chess fully observable but poker only partially observable?

In chess, both players can see the entire board state at all times - nothing is hidden. In poker, each player's hole cards are hidden from opponents, so no single agent has access to the complete game state at any instant - hence partial observability.

1.5

Concept of Rationality in AI

πŸ“˜ Definition - Rational Agent

For each possible percept sequence, a rational agent should select an action that is expected to maximize its performance measure, given the evidence provided by the percept sequence so far and whatever built-in knowledge the agent has.

Note the careful wording: rationality is about expected outcomes given available information - not about omniscience or guaranteed success. A rational agent that makes the statistically best bet can still lose due to bad luck; that does not make it irrational.

The Four Factors That Determine Rationality

  1. Performance measure defining degree of success
  2. Agent's prior knowledge of the environment
  3. Actions the agent can perform
  4. Agent's percept sequence up to the current instant
Rational Action = argmaxaction E[ Performance Measure | percept sequence, prior knowledge ]

Rationality vs. Omniscience vs. Perfection

ConceptMeaningDoes AI require it?
RationalityDoing the best possible given current informationYes - the design goal
OmniscienceKnowing the actual outcome of every action in advanceNo - impossible in practice
PerfectionAlways achieving the best actual (not expected) outcomeNo - not required, only expected-best matters
ClairvoyancePredicting the future with certaintyNo

Related Concepts: Autonomy and Learning

A rational agent should not just act on built-in knowledge - it should also be autonomous: capable of learning from percepts to compensate for incomplete or incorrect prior knowledge. An agent that relies wholly on a designer's prior knowledge, ignoring its own percepts, lacks autonomy.

πŸ’‘ Real-world example

A rational vacuum-cleaning robot that sucks dirt in a room it perceives as dirty is being rational even if, unknown to it, more dirt is hidden in a sealed cupboard - it cannot perceive that dirt, so failing to clean it does not make the agent irrational.

⚠ Common Misconception

Rationality β‰  "always succeeds." A rational poker-playing agent that folds a statistically weak hand and still would have won that particular round (due to bluffing or luck) made the rational decision - judged on expected value, not the single observed outcome.

Key Points

  • Rationality = maximizing expected performance, not guaranteeing success.
  • Determined by 4 factors: performance measure, prior knowledge, actions, percept sequence.
  • Rational agents should ideally also be autonomous (learn from experience).
Q. Can a rational agent ever make a "wrong" decision that leads to a bad outcome?

Yes. Rationality is judged by whether the action was the best choice given the information available at decision time, not by the actual outcome. An agent can make the rational choice and still suffer a bad outcome due to environmental stochasticity or hidden information.

Q. Why is autonomy important for a rational agent?

No designer can anticipate every situation an agent will face. An autonomous agent that learns from its own percepts can adapt to circumstances its built-in knowledge didn't cover, making its long-run behavior closer to truly rational.

1.6

Structure of Agents: Problem-Solving Agents

πŸ“˜ Definition

A problem-solving agent is a goal-based agent that decides what to do by finding a sequence of actions - a plan - that leads from its current state to a goal state, before executing any of those actions. This decoupling of planning from execution is called offline search.

Four-Step Problem-Solving Process

  1. Goal Formulation - based on the current situation, decide what condition(s) define success.
  2. Problem Formulation - decide what actions and states to consider, abstracting away irrelevant detail (this is also called the abstraction step).
  3. Search - before taking any real action, simulate sequences of actions in the model to find one that reaches the goal; this produces a solution.
  4. Execution - carry out the action sequence produced by the search, assuming the environment is static and predictable enough for an "open-loop" plan to remain valid throughout execution.

The Five Components of a Formally Defined Problem

ComponentDescriptionExample: 8-Puzzle
Initial StateThe state the agent starts inThe puzzle's starting tile arrangement
Actions / Successor FunctionDescription of possible actions available, ACTIONS(s), and the result of taking them, RESULT(s,a)Slide blank Up/Down/Left/Right
Goal TestDetermines whether a given state is a goal stateDoes the arrangement match the target configuration?
Path CostA function assigning a numeric cost to each path, usually the sum of step costs1 per tile move (uniform step cost)
State SpaceThe set of all states reachable from the initial state via any sequence of actionsAll reachable tile permutations
πŸ’‘ Worked example - Romania Travel Problem (classic textbook example)

An agent in Arad must reach Bucharest. States = cities; Actions = drive to an adjacent city; Goal test = "is current city Bucharest?"; Path cost = sum of road distances. Search explores combinations of routes to find the cheapest path Arad β†’ … β†’ Bucharest.

Key Points

  • Problem-solving = Goal formulation β†’ Problem formulation β†’ Search β†’ Execution.
  • A formally defined problem needs all 5 components: initial state, actions, goal test, path cost, state space.
  • This is "offline" / open-loop search - the agent commits to a full plan before acting (contrast with online search agents, Module 2).
Q. What is the difference between "search" and "execution" in problem-solving agents?

Search is the simulation phase: the agent internally explores possible action sequences using a model of the world to find a solution path, without taking real-world action. Execution is the subsequent phase where the agent actually carries out the found action sequence in the real environment.

1.7

Representation of Problems in AI

Once a problem is formally defined (Topic 1.6), it must be represented in a way that a search algorithm can process. The most common representation is the state-space graph.

πŸ“˜ Definition - State Space

The state space is a graph in which nodes represent states of the problem and edges represent actions connecting one state to another. A path through this graph from the initial state to a goal state is a solution.

State-Space Graph for the 8-Puzzle (excerpt)

S
↑
↓
←
β†’

Fig 1.4 - Root = initial tile arrangement; each child = result of one legal blank-tile move (4 possible actions, fewer near edges)

Search Tree vs. State Space (frequently confused pair)

AspectState SpaceSearch Tree
StructureA graph - can have cycles, multiple paths to the same stateA tree - generated by the search algorithm, no cycles by construction
SizeFixed by the problem itselfCan be infinite even if the state space is finite, if repeated states aren't checked
Nodes representDistinct world statesPaths from the initial state (a state may appear in multiple tree nodes)

Key Data Structures in Representation

  • Node - a data structure with: state, parent node, action taken to reach it, and path cost g(n).
  • Frontier (Open list / Fringe) - the set of all generated-but-not-yet-expanded nodes, typically a queue.
  • Explored set (Closed list) - the set of already-expanded states, used to avoid re-expanding and looping.
Pseudocode
function TREE-SEARCH(problem):
    frontier ← {Node(problem.INITIAL_STATE)}
    loop:
        if frontier is empty: return failure
        node ← REMOVE-CHOICE(frontier)         # strategy-dependent
        if problem.GOAL-TEST(node.state): return SOLUTION(node)
        for each action in problem.ACTIONS(node.state):
            child ← CHILD-NODE(problem, node, action)
            add child to frontier
πŸ”‘ Key Points
  • State space = the actual problem graph; search tree = the exploration structure built on top of it.
  • Node β‰  State: a node also stores parent, action, path cost, depth.
  • Frontier and explored set together define a search algorithm's memory footprint.
Q. Why can a search tree be infinite even when the underlying state space is finite?

If the algorithm doesn't check for repeated states, it can generate the same state again and again along different paths (e.g., going Aβ†’Bβ†’Aβ†’B→…), creating infinitely long branches in the search tree even though only a handful of distinct states actually exist.

1.8

Uninformed Search: Breadth-First Search (BFS)

BFS is the first of three uninformed (blind) search strategies in this module. "Uninformed" means the algorithm has no domain-specific knowledge beyond the problem definition itself - no heuristic guesses about which direction looks promising (that's Module 2's job). All three strategies here only know: the current state, its neighbors, and whether a state is a goal.

πŸ“˜ Definition

Breadth-First Search expands the shallowest unexpanded node first. It explores the state space level by level - all nodes at depth d are expanded before any node at depth d+1. The frontier is implemented as a FIFO queue (First-In-First-Out).

Step-by-Step Working

  1. Insert the root (initial state) into a FIFO queue.
  2. If the queue is empty, return failure.
  3. Dequeue the front node. If it is the goal, return success.
  4. Otherwise, generate all of its children (successors) and enqueue them at the back.
  5. Repeat from step 2.

Worked Example

Consider this tree, searched for goal node G:

A
B
C
D
E
G
F

Fig 1.5 - BFS visits A, then B, C (level 1), then D, E, G, F (level 2) - found in level order: A→B→C→D→E→G

Traversal order: A β†’ B β†’ C β†’ D β†’ E β†’ G (search stops as soon as G is dequeued/goal-tested). Note: BFS finds G at depth 2 only after exhausting all of depth 1 and the earlier depth-2 siblings in FIFO order.

Python
from collections import deque

def bfs(graph, start, goal):
    frontier = deque([[start]])      # queue of paths
    explored = set()
    while frontier:
        path = frontier.popleft()    # FIFO: pop from the left
        node = path[-1]
        if node == goal:
            return path
        if node not in explored:
            explored.add(node)
            for neighbor in graph[node]:
                new_path = list(path)
                new_path.append(neighbor)
                frontier.append(new_path)
    return None   # failure

graph = {'A':['B','C'], 'B':['D','E'], 'C':['G','F'], 'D':[], 'E':[], 'G':[], 'F':[]}
print(bfs(graph, 'A', 'G'))   # ['A', 'C', 'G']

Properties of BFS (the "4 properties" every search algorithm is graded on)

PropertyBFS ResultExplanation
CompletenessYes (if b is finite)Guaranteed to find a solution if one exists, since it systematically explores every depth
OptimalityYes - only if step costs are equal/uniformFinds the shallowest goal, which is the cheapest only when all edges cost the same
Time ComplexityO(bd)b = branching factor, d = depth of shallowest goal
Space ComplexityO(bd)Must store the entire frontier - this is BFS's biggest weakness
⚠ Exam Trap

Students often forget the caveat: BFS is optimal only when all step costs are identical. If step costs differ, BFS may return a shallower but more expensive path instead of the cheapest one - that's exactly the gap Uniform Cost Search (1.10) closes.

βœ“ Advantages
  • Guaranteed to find the shortest path (in terms of number of edges)
  • Complete - will always find a solution if one exists in a finite space
  • Simple to implement using a queue
βœ— Disadvantages
  • Exponential space complexity - memory is usually the limiting factor before time is
  • Not optimal when step costs vary
  • Wastes effort exploring all of a shallow level even if the goal is "obviously" nearby down one branch

Applications

  • Finding shortest path in an unweighted graph (e.g., social network "degrees of separation")
  • Web crawlers (level-by-level crawling)
  • GPS navigation systems for unweighted road networks
  • Peer-to-peer networks (finding nearest peer)
  • Puzzle solvers where all moves have equal cost (e.g., simplified 8-puzzle)
πŸ”‘ Key Points
  • BFS uses a FIFO queue - defining characteristic to remember for MCQs.
  • Complete always (finite b); optimal only with uniform step costs.
  • Time and space are both O(bd) - space is usually the bottleneck.

Interview & Exam Questions

Q. Why is BFS's space complexity considered its main drawback compared to its time complexity?

Both are O(b^d), but in practice, available memory is exhausted long before the equivalent time budget would be. For example, with b=10 and d=12, BFS needs to store roughly 10^12 nodes - far beyond typical RAM - even though, given unlimited memory, the time required would "only" be proportional to that same huge number of node expansions.

Q. Give an example where BFS fails to return the optimal-cost solution.

If node A connects directly to goal G via an edge of cost 100, but also connects to B (cost 1) which connects to G (cost 1), BFS - which only counts edges, not costs - may return the 1-edge path A→G (cost 100) instead of the 2-edge path A→B→G (cost 2), since BFS prefers the shallower solution regardless of cost.

Q. What data structure underlies BFS, and why is it essential to the algorithm's behavior?

A FIFO queue. Because new nodes are added to the back and removed from the front, all nodes at the current depth are fully processed before any node at the next depth is processed - this strict level-order processing is precisely what gives BFS its shortest-path guarantee.

1.9

Uninformed Search: Depth-First Search (DFS)

πŸ“˜ Definition

Depth-First Search always expands the deepest unexpanded node first. It dives down one branch of the tree as far as possible before backtracking to try alternatives. The frontier is implemented as a LIFO stack (Last-In-First-Out) - or equivalently via recursion.

Step-by-Step Working

  1. Push the root node onto a stack.
  2. If the stack is empty, return failure.
  3. Pop the top node. If it is the goal, return success.
  4. Otherwise, push its (unvisited) children onto the stack.
  5. Repeat from step 2, always exploring the most recently pushed node next.

Worked Example (same tree as BFS, for direct comparison)

A
B
C
D
E
G
F

Fig 1.6 - DFS plunges A→B→D first (leftmost path) before ever backtracking to try C

Traversal order: A β†’ B β†’ D (dead end, backtrack) β†’ E (dead end, backtrack) β†’ C β†’ G (goal found!). Notice DFS explores the entire left subtree before even looking at C - very different from BFS's level-order visit.

Python
def dfs(graph, start, goal, path=None, visited=None):
    if path is None: path = [start]
    if visited is None: visited = set()
    visited.add(start)
    if start == goal:
        return path
    for neighbor in graph[start]:
        if neighbor not in visited:
            result = dfs(graph, neighbor, goal, path + [neighbor], visited)
            if result:
                return result
    return None   # backtrack

graph = {'A':['B','C'], 'B':['D','E'], 'C':['G','F'], 'D':[], 'E':[], 'G':[], 'F':[]}
print(dfs(graph, 'A', 'G'))   # ['A', 'C', 'G']

Properties of DFS

PropertyDFS ResultExplanation
CompletenessNo (in infinite/cyclic spaces); Yes in finite spaces with repeated-state checkingCan get stuck going down an infinite branch and never backtrack to find the goal
OptimalityNoFinds the first goal encountered along a deep path, not necessarily the cheapest or shallowest
Time ComplexityO(bm)m = maximum depth of the search tree (can be much worse than BFS's d if m ≫ d)
Space ComplexityO(bΒ·m)Only needs to store a single path plus siblings - DFS's biggest advantage over BFS
⚠ Exam Trap - DFS vs BFS Space Complexity

This is one of the most frequently asked comparison questions: BFS needs O(b^d) space (exponential), while DFS needs only O(bΒ·m) space (linear in depth) - DFS's much smaller memory footprint is its single biggest advantage, even though it sacrifices completeness and optimality.

βœ“ Advantages
  • Linear space complexity O(bΒ·m) - far better than BFS for deep/wide trees
  • Can find a solution without exploring the entire state space
  • Simple to implement recursively, well-suited to systems with limited memory
βœ— Disadvantages
  • Not complete in infinite-depth or cyclic spaces (can loop forever down one branch)
  • Not optimal - first solution found may not be the cheapest/shortest
  • Can get "trapped" exploring a very deep, irrelevant branch

Variant: Depth-Limited Search & Iterative Deepening

To fix DFS's incompleteness, Depth-Limited Search (DLS) imposes a maximum depth limit β„“, refusing to expand nodes beyond that depth. Iterative Deepening DFS (IDDFS) repeatedly runs DLS with increasing limits (0,1,2,…) - combining DFS's low memory use with BFS's completeness and optimality (under uniform costs), at the cost of re-expanding shallow nodes multiple times.

Applications

  • Maze and puzzle solving (where memory is constrained)
  • Topological sorting and cycle detection in graphs
  • Solving constraint satisfaction problems via backtracking (Module 4)
  • Finding connected components in a graph
  • Generating game trees in game-playing AI (Module 4's Minimax)
πŸ”‘ Key Points
  • DFS uses a LIFO stack (or recursion) - defining characteristic.
  • Space O(bΒ·m) is DFS's headline advantage over BFS's O(bd).
  • Not complete (infinite spaces) and not optimal - major weaknesses vs. BFS.
  • Iterative Deepening DFS combines DFS's space efficiency with BFS's completeness.

Interview & Exam Questions

Q. Compare BFS and DFS across completeness, optimality, time, and space.

BFS: complete (finite b), optimal (uniform costs), O(b^d) time, O(b^d) space. DFS: not complete (infinite/cyclic spaces), not optimal, O(b^m) time, O(bΒ·m) space. The defining trade-off: DFS trades correctness guarantees for drastically lower memory usage.

Q. Why might DFS perform worse than BFS in terms of time, even though both are O(b^something)?

DFS's bound is O(b^m) where m is the maximum depth of the entire tree, which can be far larger than d, the depth of the shallowest goal (BFS's bound). If the tree has a very deep irrelevant branch, DFS may explore it entirely before backtracking to find a much shallower goal.

Q. What problem does Iterative Deepening DFS solve, and how?

It solves DFS's incompleteness/non-optimality while keeping DFS's low memory usage. It runs depth-limited DFS repeatedly with limit = 0, 1, 2, … until a goal is found - guaranteeing the shallowest (and, under uniform costs, cheapest) goal is found first, just like BFS, but using only O(bΒ·d) memory.

1.10

Uninformed Search: Uniform Cost Search (UCS)

πŸ“˜ Definition

Uniform Cost Search expands the node with the lowest path cost g(n) from the start - not the shallowest, as in BFS. It generalizes BFS to work correctly when edges have different (non-uniform) costs. The frontier is a priority queue ordered by cumulative path cost.

UCS is essentially identical to Dijkstra's Algorithm from graph theory, applied within the search-agent framework, stopping as soon as a goal node is dequeued (rather than computing shortest paths to every node).

Step-by-Step Working

  1. Insert the root with g(root) = 0 into a priority queue ordered by g(n).
  2. If the queue is empty, return failure.
  3. Remove the node with the smallest g(n). Perform the goal test at expansion time (not at insertion time - this distinction is crucial for correctness).
  4. If it's the goal, return success.
  5. Otherwise, expand it: for each child, compute g(child) = g(parent) + step cost. If the child is new, or found via a cheaper path than previously recorded, insert/update it in the priority queue.
  6. Repeat from step 2.
⚠ Critical Detail Often Missed

UCS must test for the goal when a node is selected for expansion, not when it is first generated. Testing too early can return a more expensive path, since a cheaper path to the same goal node might still be sitting in the frontier.

Worked Example

S
A (g=1)
B (g=4)
C (g=1+5=6)
G (g=1+2=3)

Fig 1.7 - Even though B's direct edge (cost 4) looks attractive, UCS finds S→A→G costs only 3, cheaper than any path through B; total path cost is minimized, not edge count

UCS frontier evolves as: {S(0)} → expand S → {A(1), B(4)} → expand A (lowest g) → {B(4), G(3), C(6)} → expand G (lowest g=3, and it's the goal) → return path S→A→G, cost 3. Notice B (cost 4) was never expanded, and the algorithm correctly preferred the cheaper 2-hop path over a tempting 1-hop alternative.

Python
import heapq

def ucs(graph, start, goal):
    # graph[node] = list of (neighbor, cost)
    frontier = [(0, start, [start])]   # (path_cost, node, path)
    explored = set()
    while frontier:
        cost, node, path = heapq.heappop(frontier)
        if node == goal:
            return path, cost
        if node in explored:
            continue
        explored.add(node)
        for neighbor, step_cost in graph.get(node, []):
            if neighbor not in explored:
                heapq.heappush(frontier, (cost + step_cost, neighbor, path + [neighbor]))
    return None, float('inf')

graph = {'S':[('A',1),('B',4)], 'A':[('G',2),('C',5)], 'B':[('G',1)]}
print(ucs(graph, 'S', 'G'))   # (['S', 'A', 'G'], 3)

Properties of UCS

PropertyUCS ResultExplanation
CompletenessYes, provided step costs β‰₯ small positive constant Ξ΅ > 0Prevents infinite regress down a path of ever-shrinking costs
OptimalityYes - alwaysWorks correctly regardless of whether step costs are equal, unlike BFS
Time ComplexityO(b1+⌊C*/Ξ΅βŒ‹)C* = cost of optimal solution; effectively similar to BFS when costs are near-uniform
Space ComplexityO(b1+⌊C*/Ξ΅βŒ‹)Same exponential frontier-storage issue as BFS

BFS vs UCS - The Most-Asked Comparison

AspectBFSUCS
Frontier structureFIFO QueuePriority Queue (min-heap by g(n))
Expansion orderShallowest node firstCheapest cumulative cost first
Optimal when costs are equal?YesYes
Optimal when costs differ?NoYes
Special case relationshipBFS = UCS when all step costs are equal (UCS reduces to BFS)
βœ“ Advantages
  • Always finds the optimal (lowest-cost) solution, regardless of step-cost variation
  • Complete under mild assumptions (positive minimum step cost)
  • Generalizes BFS - strictly more broadly applicable
βœ— Disadvantages
  • Same exponential time/space complexity issues as BFS
  • No knowledge of goal direction - explores "uninformed," wasting effort versus heuristic search (A*, Module 2)
  • Can be slow if many low-cost edges exist far from the goal

Applications

  • Shortest path in weighted graphs (road networks with real distances/times)
  • Network routing protocols
  • Currency arbitrage / cheapest-flight-style search problems
  • Lab Experiment 6(ii) of this course: "Shortest path problem using Lowest-Cost-First Search"
πŸ”‘ Key Points
  • UCS = BFS generalized to weighted edges; frontier is a priority queue by g(n).
  • Goal test happens at expansion, not generation - a key correctness detail.
  • UCS is always optimal and complete (given Ξ΅ > 0); BFS is only optimal for uniform costs.
  • UCS ≑ Dijkstra's Algorithm stopped early at the goal.

Interview & Exam Questions

Q. How does UCS differ from BFS when all edge costs are equal to 1?

They behave identically. When every step cost is the same constant, the lowest-cumulative-cost node is always also the shallowest node, so UCS's priority-queue ordering collapses to exactly BFS's FIFO ordering. BFS is a special case of UCS.

Q. Why must UCS test for the goal only when a node is popped for expansion, not when generated?

A node might first be reached via an expensive path and inserted into the frontier, while a cheaper path to that same node is discovered later. If the goal test were applied at insertion, UCS could return the first-discovered (expensive) path instead of waiting to confirm it really is the cheapest path once it reaches the front of the priority queue.

Q. Is UCS related to Dijkstra's algorithm? How?

Yes - UCS is essentially Dijkstra's single-source shortest path algorithm, restricted to search from one start state and terminated as soon as a designated goal node is expanded, rather than computing shortest distances to every node in the graph.

πŸ“‹ Module 1 - Complete Summary

Module 1 established AI as the science of building rational agents - formally defined by performance measure, prior knowledge, actions, and percept sequence - operating within environments described via PEAS and six observability/determinism/structure properties. We saw AI's history move through two "winters" before today's data-driven resurgence, and learned to distinguish Narrow AI (all of today's deployed systems) from the still-hypothetical AGI. Finally, we formalized "problem-solving" as a 4-step process (goal formulation β†’ problem formulation β†’ search β†’ execution) over a 5-component formal problem definition, and studied the first family of search algorithms - BFS (FIFO, optimal only for uniform costs), DFS (LIFO, memory-efficient but incomplete), and UCS (priority queue by path cost, always optimal) - the baseline every later algorithm in this course will be compared against.