1.Intelligent Agents & Environments
The central unifying concept of modern Artificial Intelligence is the intelligent agent. Rather than defining AI in terms of human thought processes or internal subjective consciousness, AI is formulated as the computational science of designing systems that act rationally. An agent interacts with an environment through a closed perceptual-action loop: it perceives the environment via sensors and alters that environment via actuators.
1.1Agents, Percepts & Actions
Formally, an agent is anything that can view its environment through sensors and act upon that environment through actuators. A human agent has eyes, ears, and other organs for sensors; hands, legs, vocal tract for actuators. A robotic agent might substitute cameras, infrared range finders, and lidars for sensors, and electric motors or hydraulic joints for actuators. A software agent (or softbot) receives keystrokes, network packets, or file contents as sensor inputs and acts upon the environment by sending network packets, writing files, or displaying graphics.
We use the term percept to refer to the agent's perceptual inputs at any given instant. An agent's percept sequence is the complete history of everything the agent has ever perceived:
Mathematically, an agent's behavior is described by the agent function f, which maps any given percept sequence to an action a ∈ A:
The agent function is an abstract mathematical description. The agent program is the concrete implementation of f that executes on a physical architecture (a computing device with physical sensors and actuators):
1.2Good Behavior: The Concept of Rationality
What does it mean for an agent to behave well? A rational agent is one that does the right thing — conceptually, every entry in the table for the agent function is filled out correctly. To make this precise, we define a performance measure that embodies the criterion for success.
Formally, rationality is defined by four factors:
- The performance measure that defines the criterion of success.
- The agent's prior knowledge of the environment.
- The actions that the agent can perform.
- The agent's percept sequence to date.
Three critical distinctions must be maintained when discussing rationality:
- Rationality vs. Omniscience: An omniscient agent knows the actual outcome of its actions and can act accordingly; but omniscience is impossible in reality. Rationality maximizes expected performance, whereas perfection maximizes actual outcome. If an agent looks both ways, sees a clear street, steps out, and is hit by an unforeseen meteorite falling from orbit, the agent was fully rational even though the outcome was tragic.
- Information Gathering & Exploration: Doing actions in order to modify future percepts (e.g., looking both ways before crossing, exploring unfamiliar terrain) is a fundamental part of rationality.
- Autonomy: An agent is autonomous to the extent that its behavior is determined by its own experience (with ability to learn and adapt), rather than solely by the built-in knowledge of its designer. A truly autonomous agent should be able to operate across different environments given sufficient time to learn.
1.3Specifying Task Environments: PEAS
In designing an AI agent, the very first step is always to specify the task environment as fully as possible. AIMA organizes this specification under the PEAS framework:
- Performance Measure: The objective metrics used to evaluate the agent's behavior.
- Environment: The external world, context, physical systems, or software ecosystem the agent operates in.
- Actuators: The devices or interfaces through which the agent acts.
- Sensors: The devices or interfaces through which the agent receives percepts.
| Agent Type | Performance Measure | Environment | Actuators | Sensors |
|---|---|---|---|---|
| Automated Taxi Driver | Safe, fast, legal, comfortable trip, maximize profits, minimize wear | Roads, traffic, pedestrians, weather, customers, police | Steering wheel, accelerator, brake, signal indicators, horn, display | Cameras, sonar, radar, lidar, GPS, speedometer, engine sensors, accelerometer |
| Vacuum-Cleaner Agent | Cleanliness, time spent, electricity consumed, noise level | Rooms, dirt, furniture, walls, floor types | Wheels, brushes, vacuum motor, trash ejection mechanism | Dirt sensor, bump sensor, infrared cliff sensor, wheel encoders |
| Medical Diagnosis System | Healthy patient, minimize costs, avoid malpractice/adverse reactions | Patient, hospital staff, medical testing equipment | Display screen (questions, test recommendations, diagnoses, prescriptions) | Keyboard input (symptoms, lab results, patient vital signs, medical history) |
| Part-Picking Robot | Percentage of parts in correct bins, speed, avoid part damage | Conveyor belt with parts, storage bins | Jointed robotic arm, gripper hand | Camera, tactile force sensors, joint angle encoders |
| Interactive English Tutor | Student test score improvement, engagement, student satisfaction | Set of students, curriculum testing platform | Screen display (exercises, explanations, corrections, suggestions) | Keyboard and mouse input, audio microphone |
1.4Environment Characteristics & Dimensions
The nature of the environment largely dictates the design of the agent program and the feasibility of different problem-solving methods. AIMA classifies task environments along seven primary dimensions:
- Fully Observable vs. Partially Observable
- An environment is fully observable if the agent's sensors give it access to the complete state of the environment at each point in time (e.g., Chess, 8-Puzzle). It is partially observable if sensors are noisy, inaccurate, or missing state data (e.g., Poker, Driving in fog). An environment is unobservable if the agent has no sensors at all.
- Single-Agent vs. Multi-Agent
- An agent solving a Crossword puzzle is in a single-agent environment. Chess is a multi-agent competitive environment (zero-sum game). Autonomous driving is a multi-agent partially cooperative / partially competitive environment (avoiding collisions is cooperative; claiming a parking spot is competitive).
- Deterministic vs. Stochastic
- If the next state of the environment is completely determined by the current state and the action executed by the agent, the environment is deterministic (e.g., 8-Puzzle, Maze). If randomness or probabilities affect outcomes, it is stochastic (e.g., Backgammon dice rolls, Taxi driving). If the environment cannot be predicted deterministically but lacks explicit probabilities, it is nondeterministic.
- Episodic vs. Sequential
- In an episodic environment, the agent's experience is divided into atomic episodes; the choice of action in each episode depends only on the episode itself, and current decisions do not affect future episodes (e.g., classifying defective parts on an assembly line). In a sequential environment, current decisions affect all future decisions (e.g., Chess, Route Finding).
- Static vs. Dynamic
- If the environment can change while the agent is deliberating, it is dynamic (e.g., Taxi driving, real-time strategy games). If it does not change with the passage of time, it is static (e.g., Crossword puzzle, 8-Puzzle). An environment is semidynamic if the environment itself doesn't change, but the agent's performance score decreases over time (e.g., timed Chess).
- Discrete vs. Continuous
- Pertains to the state of the environment, the way time is handled, and the percepts and actions. Chess has a discrete state space and discrete turns; Taxi driving has continuous states (locations, speed, angles) and continuous time and actions.
- Known vs. Unknown
- Refers to the agent's knowledge of the laws of physics or rules of the environment. In a known environment, the outcomes for all actions are known (e.g., standard Solitaire); in an unknown environment, the agent must learn how the world works in order to make good decisions.
1.5Agent Architectures: From Reflex to Learning
AIMA defines five canonical agent program structures, arranged in increasing order of generality and sophistication:
- Simple Reflex Agents: Select actions based only on the current percept, ignoring the history of percepts. Implemented using
condition-action rules(e.g.,if car-in-front-is-braking then initiate-braking). Only effective in fully observable environments; unrecoverable infinite loops occur in partially observable environments. - Model-Based Reflex Agents: Maintain an internal state to track parts of the world they cannot see right now. They maintain two models: transition model ("how the world evolves independently and how my actions change it") and sensor model ("how the state of the world reflects into my percepts").
- Goal-Based Agents: Combine current state information with a goal description to select actions that achieve the desired outcome. This enables search and planning — the central topic of Chapter 3 and Topic 01.
- Utility-Based Agents: Use a real-valued utility function
U(s) ∈ ℝto measure how desirable a state is. Allows rational decision-making when goals conflict, when trade-offs must be made (e.g., speed vs. safety), or when multiple goals can only be achieved with uncertainty. - Learning Agents: Can operate in initially unknown environments and become more competent than their initial programming. Divided into four components:
- Learning Element: Responsible for making improvements based on experience.
- Performance Element: Responsible for selecting external actions (corresponds to the entire agent in the previous structures).
- Critic: Evaluates how well the agent is doing against an external, fixed performance standard.
- Problem Generator: Suggests exploratory actions that lead to new experiences and improved long-term performance.
2.The Formal Problem Formulation Framework
When an agent cannot simply react to its immediate environment with a single hard-coded reflex rule, it must look ahead and formulate a plan. A problem-solving agent is a goal-based agent that decides what to do by finding sequences of actions that lead to desirable states.
2.1Problem-Solving Agents & Goal Formulation
The problem-solving cycle follows a rigorous four-phase sequence:
1. Goal Formulation: Organize objectives into a concrete target based on current situation. 2. Problem Formulation: Decide what actions and states to consider, given the goal. 3. Search: Simulate action sequences in the abstract state space until a goal path is found. 4. Execution: Execute the planned actions one by one in the real physical world.
Crucially, search is performed offline: the agent explores hypothetical paths within its mental model of the world before executing a single physical action. Once a solution is found, the execution phase begins.
2.2The 5 Components of a Search Problem
Formally, a search problem is defined by five mathematical components — often packaged as a formal 5-tuple (s₀, ACTIONS, RESULT, IS-GOAL, STEP-COST):
- 1. Initial State
- The state that the agent starts in, denoted
s₀ ∈ S. - 2. Actions
- A function
ACTIONS(s)that returns the set of legal actions that can be executed when in states. Ifa ∈ ACTIONS(s), actionais applicable in states. - 3. Transition Model
- A function
RESULT(s, a) = s′that returns the states′that results from doing actionain states. We say thats′is a successor ofs. - 4. Goal Test
- A predicate
IS-GOAL(s)that determines whether a given statesis a goal state. The goal can be an explicit set of enumerated states{g₁, g₂, …}or an abstract property test (e.g.,no_two_queens_attack_each_other(board)). - 5. Path Cost & Step Cost
- A function
c(s, a, s′)that assigns a numeric cost to taking actionain statesto reachs′. The total path costg(n)of a sequence of actions is the sum of the individual step costs along the path.
2.3States vs. Physical World: The Art of Abstraction
A physical environment is overwhelmingly complex, continuous, and filled with infinite irrelevant details. An agent navigating a city does not need to model the current tire air pressure, the song playing on the radio, the temperature of the asphalt, or the color of the adjacent vehicle. Including these details would make the state space infinitely large and completely unsearchable.
Abstraction is the process of removing irrelevant detail from the state representation while preserving everything required to find a valid solution:
An abstraction is valid if any abstract action sequence can be translated into a sequence of physical actions that actually succeeds in the real world. An abstraction is useful if carrying out actions in the abstract representation is computationally easier than searching the raw physical environment.
2.4State Space & Reachability
Together, the initial state, actions, and transition model implicitly define the state space S of the problem. The state space is the set of all states reachable from the initial state by any sequence of valid actions.
The state space forms a directed graph in which the nodes are states and the directed edges (links) between them are actions. A path in the state space is a sequence of states connected by a sequence of actions.
2.5Solutions, Path Costs & Optimality
A solution to a search problem is an action sequence that leads from the initial state s₀ to any state s satisfying IS-GOAL(s) == true.
An optimal solution is a solution that has the lowest path cost among all possible solutions. The cost of the optimal solution is denoted C*:
3.Benchmark Problem Formulations
AI problems are traditionally divided into toy problems (intended to illustrate or exercise various problem-solving methods, with concise, exact descriptions) and real-world problems (whose solutions people actually care about, often requiring complex domain engineering). Below are the classic formulations from AIMA and the interactive lecture.
3.1The Two-Room Vacuum World
The Two-Room Vacuum World is the quintessential toy problem introduced in AIMA Chapter 2. The environment consists of two locations: Room A (left) and Room B (right). Each room can be either Clean or Dirty. The vacuum agent is located in either Room A or Room B.
- States
- Determined by agent location and status of both rooms:
2 × 2 × 2 = 8discrete states:(Location, RoomA_status, RoomB_status). - Initial State
- Any of the 8 states (e.g.,
(A, Dirty, Dirty)). - Actions
{Left, Right, Suck}.- Transition Model
Leftmoves agent to A;Rightmoves agent to B;Suckcleans the current room. Moving into a wall has no effect.- Goal Test
- Both rooms are clean:
RoomA == Clean ∧ RoomB == Clean(States 7 and 8). - Path Cost
- Each step costs 1 (number of actions taken).
3.2The 8-Puzzle & Sliding Tile Puzzles
The 8-puzzle consists of a 3 × 3 board with 8 numbered tiles and one blank space (represented by 0). A tile adjacent to the blank space can slide into the blank space.
- States
- A configuration specifying the location of each of the 8 tiles and the blank in the nine squares. Total permutations:
9! = 362,880. Exactly half (9! / 2 = 181,440) are reachable from any initial configuration due to the permutation parity invariant. - Initial State
- Any designated valid board configuration.
- Actions
- Move the blank space
Left,Right,Up, orDown(conventionally modeled as moving the blank rather than moving tiles, which keeps the action set fixed to ≤ 4). - Transition Model
- Swaps the blank with the tile in the target direction, returning the new board state.
- Goal Test
- Board matches the target solved configuration (e.g.
[1,2,3, 4,5,6, 7,8,0]). - Path Cost
- Each step costs 1 (total moves).
3.32D Grid & Maze Navigation
An agent navigates a discrete 2D grid from a starting cell to a goal cell, avoiding obstacles and walls.
- States
- Grid coordinate
(x, y)or(row, col)representing the agent's current location. - Initial State
- Designated start coordinate
(row₀, col₀). - Actions
- Move
{North, South, East, West}to adjacent in-bounds, non-wall cells. - Transition Model
RESULT((r, c), North) = (r - 1, c), etc.- Goal Test
(r, c) == (r_goal, c_goal).- Path Cost
- 1 per movement step (or Manhattan/Euclidean distance in weighted terrain).
3.4Route Finding & Road Networks
The canonical route-finding problem from AIMA: an agent is in the city of Arad, Romania, and wishes to travel to Bucharest along a road network with specified distances.
- States
- The name of the current city (e.g.,
Arad,Sibiu,Bucharest). - Initial State
In(Arad).- Actions
Go(c)for any citycdirectly connected to the current city by a road.- Transition Model
RESULT(In(Arad), Go(Zerind)) = In(Zerind).- Goal Test
s == In(Bucharest).- Path Cost
- Sum of the road distances in kilometers (e.g.,
c(Arad, Go(Zerind), Zerind) = 75 km). Note: Unlike the previous examples, step costs are non-unit, so number of actions and total path cost diverge!
3.5The 8-Queens Problem
The goal of the 8-Queens problem is to place 8 queens on a chessboard such that no queen attacks any other queen (no two queens share the same row, column, or diagonal).
This problem highlights the critical design choice between two formulation styles:
| Formulation Style | State Representation | Actions | State Space Size |
|---|---|---|---|
| Naive Incremental | Arrangement of 0 to 8 queens on the board | Add a queen to any empty square | 64 × 63 × … × 57 ≈ 1.8 × 10¹⁴ states |
| Refined Incremental (Column-by-column) | Placement of k queens in the leftmost k columns, 1 per column |
Add a queen to an unattacked square in column k + 1 |
2,057 reachable valid states |
| Complete-State Formulation | All 8 queens placed on board (1 per column) | Move an attacked queen to another row in its column | 8⁸ = 16,777,216 states (Local search / CSP) |
3.6Real-World Problem Formulations
While toy problems provide clean conceptual models, real-world problems drive industry applications:
- Traveling Salesperson Problem (TSP): A touring problem where every city on a map must be visited exactly once with minimal total mileage. Total candidate tours for
ncities is(n - 1)! / 2— NP-hard. - VLSI Layout Design: Positioning millions of transistors and routing connecting wires on a silicon chip without wire overlap, minimizing chip area and electrical capacitance delay.
- Robot Navigation: Moving a continuous kinematic manipulator or autonomous vehicle through 3D space with continuous angles and obstacles — discretized into configuration spaces.
- Automatic Assembly Sequencing: Finding a valid order to assemble complex mechanical components (e.g., jet engines) without parts colliding during assembly.
- Protein Design & Folding: Finding a sequence of amino acids that folds into a target 3D structure that cures disease or catalyzes a chemical reaction.
4.Analyzing & Comparing Formulations
Formulating a problem is not merely about writing down definitions; it is about choosing the mathematical representation that makes searching for a solution computationally tractable.
4.1State Space Size & Branching Factor
Two metrics govern the difficulty of a search problem:
- State Space Size
|S|: The total number of reachable distinct configurations. If|S|is small (e.g., 8 states in Two-Room Vacuum), exhaustive enumeration is trivial. If|S|is massive (e.g.,10²⁰in 15-puzzle,10¹²⁰in Chess), clever heuristics and pruning are mandatory. - Branching Factor
b: The number of legal actions available from a typical state. In an 8-puzzle,branges from 2 (corners) to 3 (edges) to 4 (center), with an averageb ≈ 3. In chess, averageb ≈ 35; in Go, averageb ≈ 250.
4.2State Space Graph vs. Search Tree
A frequent point of confusion is the distinction between the state space graph and the search tree:
- The state space graph has exactly one node per unique physical state in
S. Edges represent reversible or irreversible action transitions between states. If a graph has cycles (e.g.,Left → Right → Left), the state space graph remains finite. - The search tree is a tree of unrolled paths generated by a search algorithm starting at the initial state. Because the same state can be reached by infinitely many paths in a cyclic graph, the search tree can be infinite even when the state space is tiny! Graph search maintains a
reachedtable to prune these redundant paths.
4.3Atomic, Factored & Structured States
AIMA Chapter 2 introduces the three fundamental paradigms for representing states:
| Representation | Internal Structure | Example | Used In |
|---|---|---|---|
| Atomic | State has no internal substructure — it is a black box / single opaque token | Arad, State_4 |
Standard classical search (BFS, DFS, A*) |
| Factored | State is split into fixed set of variables / attributes with specific values | {Location: A, RoomA: Clean, RoomB: Dirty} |
Constraint Satisfaction (CSPs), Planning, Propositional Logic |
| Structured | State contains explicit objects, attributes, and relationships between objects | On(BlockA, BlockB) ∧ Clear(BlockA) |
First-Order Logic, Knowledge Graphs, Relational AI |
4.4Problem Formulation Comparison Matrix
The table below summarizes the formal 5-component formulation across our benchmark domains:
| Problem | State Representation | Actions | Goal Test | Step Cost | State Space Size |
|---|---|---|---|---|---|
| Two-Room Vacuum | (AgentLoc, Status_A, Status_B) |
{Left, Right, Suck} |
Status_A == Clean ∧ Status_B == Clean |
1 per action |
8 states |
| 8-Puzzle | 3 × 3 array of tiles 0..8 |
Move blank {Left, Right, Up, Down} |
Matching canonical solved board | 1 per slide |
181,440 (reachable) |
| 5×5 Grid Maze | Coordinate tuple (row, col) |
Move {N, S, E, W} into open cell |
(row, col) == (goal_r, goal_c) |
1 per step |
≤ 25 cells |
| Route Finding | City name In(City) |
Go(ConnectedCity) |
In(DestinationCity) |
Road distance in km | Number of cities (e.g. 20) |
| 8-Queens (Refined) | List of queen row positions [r₁, …, r_k] |
Place queen in next column | 8 queens placed without conflicts | 0 (or 1 per placement) |
2,057 valid states |
5.Practice Exercises
The eight exercises below provide deep conceptual and analytical practice on intelligent agents, PEAS task specifications, environment classification, state-space combinatorics, and rigorous 5-component problem formulation. Each problem is stated first; click Show Answer to view the complete worked mathematical solution.
PEAS Task Environment Specifications
Provide complete PEAS (Performance measure, Environment, Actuators, Sensors) specifications for the following three autonomous systems:
(a) Autonomous Warehouse Forklift Robot moving pallets between trucks and shelving.
(b) Automated High-Frequency Stock Trading Agent executing trades on digital financial exchanges.
(c) Smart Thermostat & Climate Control System managing energy and comfort in an office building.
Show Answer
- Performance Measure
- Number of pallets successfully moved per hour, energy efficiency, zero collisions with human workers or shelving, zero pallet damage, optimal storage density.
- Environment
- Warehouse floor, loading docks, delivery trucks, storage racks, static obstacles, moving human workers and other forklifts.
- Actuators
- Electric drive motors (steering, throttle, regenerative braking), hydraulic lift mechanism for forks, safety horn, visual strobe lights, inventory logging RF transmitter.
- Sensors
- 2D/3D Lidar scanners, depth cameras, wheel odometry encoders, pallet barcode/RFID readers, fork weight/load pressure sensors, emergency bumper switches.
- Performance Measure
- Total net return on investment (ROI), Sharpe ratio (risk-adjusted return), maximum drawdown minimization, transaction cost minimization, regulatory compliance.
- Environment
- Global electronic exchanges (NYSE, NASDAQ, CME), order books, financial news wire feeds, economic indicator releases, competitor algorithms.
- Actuators
- Electronic order submission (market, limit, stop orders, cancellations) via FIX protocol API, fund allocation adjustments.
- Sensors
- Real-time Level 2/3 market data feeds (order book depth, trade ticks), financial news text parsers, historical price database feeds.
- Performance Measure
- Thermal comfort satisfaction percentage, kilowatt-hours consumed (energy cost minimization), peak electricity demand charge reduction, HVAC equipment lifespan preservation.
- Environment
- Multi-zone office building, ambient outdoor weather, solar irradiation, occupant schedule, variable electricity tariff pricing.
- Actuators
- HVAC compressor/furnace relays, variable-speed fan controllers, motorized zone air dampers, smart window shade motors.
- Sensors
- Multi-room temperature sensors, relative humidity sensors, PIR motion / occupancy sensors, CO₂ air quality sensors, outdoor weather API, grid pricing signal.
Environment Classification Matrix
Classify the following six task environments across the 6 primary AIMA dimensions: Observability (Fully vs. Partially), Agents (Single vs. Multi), Determinism (Deterministic vs. Stochastic), Episodic (Episodic vs. Sequential), Static (Static vs. Dynamic), and Discreteness (Discrete vs. Continuous):
- Chess (with a clock)
- Texas Hold'em Poker
- Autonomous Driving
- Image Part-Defect Classifier
- Crossword Puzzle
- Medical Diagnosis System
Show Answer
| Environment | Observability | Agents | Determinism | Episodic? | Static/Dynamic | Discreteness |
|---|---|---|---|---|---|---|
| Chess (with clock) | Fully | Multi (Competitive) | Deterministic | Sequential | Semi-dynamic | Discrete |
| Texas Hold'em Poker | Partially | Multi (Competitive) | Stochastic | Sequential | Static (on turn) | Discrete |
| Autonomous Driving | Partially | Multi (Mixed) | Stochastic | Sequential | Dynamic | Continuous |
| Image Defect Classifier | Fully | Single | Deterministic | Episodic | Static | Continuous / Discrete |
| Crossword Puzzle | Fully | Single | Deterministic | Sequential | Static | Discrete |
| Medical Diagnosis | Partially | Single (or Multi) | Stochastic | Sequential | Dynamic | Continuous / Discrete |
Key Takeaways: The hardest environments for an AI agent are Partially observable, Multi-agent, Stochastic, Sequential, Dynamic, Continuous, and Unknown (such as real-world autonomous driving).
State Space Combinatorics in Generalized Vacuum Worlds
Consider a generalized Vacuum World with N distinct rooms arranged in a linear row (1 to N). The agent can be in any of the N rooms.
(a) If each room can be either Clean or Dirty, derive a formula for the total number of distinct states |S| in the state space.
(b) What is |S| for N = 2, N = 5, and N = 10 rooms?
(c) Suppose each room can have K discrete levels of dirtiness (0 = Spotless, 1 = Light Dust, ..., K - 1 = Filthy). What is the total state space size as a function of N and K?
Show Answer
A state is specified by two independent components: the vacuum's current location and the dirt status of every room.
- Agent location choices:
Npossibilities (Room 1, Room 2, …, RoomN). - Dirt status per room: 2 possibilities (
CleanorDirty). ForNindependent rooms, there are2Ntotal room status configurations.
- For
N = 2:|S| = 2 × 2² = 2 × 4 = 8states (the standard Two-Room Vacuum World). - For
N = 5:|S| = 5 × 2⁵ = 5 × 32 = 160states. - For
N = 10:|S| = 10 × 2¹⁰ = 10 × 1024 = 10,240states.
If each room has K possible dirt levels, the number of environment configurations is KN.
For example, with N = 5 rooms and K = 4 dirt levels: |S| = 5 × 4⁵ = 5 × 1024 = 5,120 states.
8-Puzzle Permutation Invariant & Solvability Proof
The 8-puzzle state space consists of all permutations of the 9 symbols {0, 1, 2, 3, 4, 5, 6, 7, 8}, totaling 9! = 362,880 arrangements. Prove why exactly half of all possible random board permutations (181,440) are solvable to the standard goal state.
Show Answer
Mathematical Proof via Permutation Inversions:
1. Flatten the 3 × 3 grid into a 1D sequence of length 8, omitting the blank tile (0). For example, the board:
1 2 3 8 _ 4 → Sequence: (1, 2, 3, 8, 4, 7, 6, 5) 7 6 5
2. Define an inversion as any pair of tiles (a, b) such that tile a appears before tile b in the sequence, but a > b. In the sequence above, the inversions involving 8 are (8,4), (8,7), (8,6), (8,5); the inversions involving 7 are (7,6), (7,5); the inversion involving 6 is (6,5). Total inversions = 4 + 2 + 1 = 7 (odd parity).
3. Effect of Legal Actions on Inversion Parity:
- Horizontal Blank Move (Left / Right): Swapping the blank horizontally with an adjacent tile does not change the relative order of any numbered tiles in the 1D sequence. ΔInversions =
0. Parity is strictly conserved. - Vertical Blank Move (Up / Down): Moving the blank vertically swaps it with a tile 3 positions away in the grid, jumping over exactly 2 intervening numbered tiles in the 1D sequence.
- If both skipped tiles were smaller (or both larger) than the moved tile, the number of inversions changes by
±2. - If one skipped tile was larger and one smaller, one inversion is gained and one lost: ΔInversions =
0. - In all cases, the change in the number of inversions is always an even integer (
Δ = -2, 0, +2).
- If both skipped tiles were smaller (or both larger) than the moved tile, the number of inversions changes by
4. Conclusion: Every legal action in the 8-puzzle preserves the parity (evenness or oddness) of the number of inversions. The standard goal state (1, 2, 3, 4, 5, 6, 7, 8) has 0 inversions (an even parity).
Because exactly 9! / 2 = 181,440 permutations have even parity and 9! / 2 = 181,440 have odd parity, the state space is partitioned into two disjoint, unconnected graph components. No sequence of legal moves can ever cross from an odd parity state to an even parity goal state.
8-Queens: Incremental vs. Complete-State Formulations
Compare two different problem formulations for the 8-Queens problem:
(a) Incremental Formulation A: Start with an empty board. Any action adds a queen to any empty square. Calculate the total number of candidate states explored up to depth 8.
(b) Incremental Formulation B (Column-by-column with conflict checking): Place a queen in column k (from left to right) only on a square that is not attacked by any previously placed queen. Why does this reduce the number of visited states to just 2,057?
(c) Complete-State Formulation C: Start with 8 queens on the board (one per column). An action moves a queen within its column. What is the size of this state space?
Show Answer
At step 1, 64 empty squares exist; at step 2, 63 squares; ... at step 8, 57 squares. The total sequences of 8 placements is:
Even ignoring placement order (combinations), C(64, 8) = 4,426,165,368 candidate final states exist — an overwhelmingly large search space for a simple puzzle.
By enforcing two constraints into the ACTIONS(s) definition itself:
- Queen
kmust be placed in Columnk(eliminates column conflicts by definition, shrinking initial space from1.8 × 10¹⁴to8⁸ = 16,777,216). - Queen
kcan only be placed on a square not attacked row-wise or diagonally by queens in columns1..k-1.
Because illegal partial paths are pruned immediately upon generation, the total number of states at all depths in the search tree is reduced to exactly 2,057 nodes (with only 92 leaf nodes reaching depth 8, representing the 92 solutions). This demonstrates how a refined formulation collapses search complexity by orders of magnitude.
Each of the 8 columns contains exactly one queen, which can be in any of the 8 rows. Total state space size:
This formulation is ideally suited for local search algorithms (like Hill-Climbing, Simulated Annealing, and Min-Conflicts CSP) where all 8 queens are iteratively moved to minimize the number of conflicting pairs.
River Crossing: Missionaries & Cannibals 5-Tuple Formulation
Three missionaries and three cannibals are on the left bank of a river, along with a boat that can hold at most two people. If the cannibals ever outnumber the missionaries on either bank of the river (including when passengers disembark), the missionaries will be eaten. Everyone wishes to cross to the right bank safely.
Provide a rigorous formal 5-component formulation of this problem: State representation, Initial state, Actions, Transition model, Goal test, and Path cost.
Show Answer
- 1. State Representation
- A 3-tuple
(M, C, B)representing the situation on the left bank:M ∈ {0, 1, 2, 3}: Number of missionaries on left bank.C ∈ {0, 1, 2, 3}: Number of cannibals on left bank.B ∈ {1, 0}: Boat position (1if on left bank,0if on right bank).
(3 - M, 3 - C, 1 - B).
Validity Constraint (Safety Condition): A state is legal if and only if:(M == 0 ∨ M ≥ C) ∧ ((3 - M) == 0 ∨ (3 - M) ≥ (3 - C)). - 2. Initial State
s₀ = (3, 3, 1)(everyone and the boat on the left bank).- 3. Actions
- Move
(m, c)people across the river where1 ≤ m + c ≤ 2. Possible boat loads:{(1, 0), (2, 0), (0, 1), (0, 2), (1, 1)}.- If
B == 1(boat on left bank):ACTIONS(s) = { Cross(m, c) : m ≤ M, c ≤ C, and RESULT is safe }. - If
B == 0(boat on right bank):ACTIONS(s) = { Return(m, c) : m ≤ 3 - M, c ≤ 3 - C, and RESULT is safe }.
- If
- 4. Transition Model
-
- If
B == 1:RESULT((M, C, 1), Cross(m, c)) = (M - m, C - c, 0). - If
B == 0:RESULT((M, C, 0), Return(m, c)) = (M + m, C + c, 1).
- If
- 5. Goal Test
IS-GOAL((M, C, B)) ≡ (M == 0 ∧ C == 0 ∧ B == 0)(everyone on right bank).- 6. Path Cost
- Unit cost
c = 1per river crossing. (Optimal solution requires exactly 11 crossings).
Validating Abstractions & the Real-World Gap
In AI problem formulation, abstraction removes irrelevant details. However, an incorrect abstraction can render a search problem either unsolvable or invalid in the real world.
(a) Explain the difference between an over-abstracted formulation and an under-abstracted formulation.
(b) Suppose you formulate route finding for an Electric Vehicle (EV) by representing state solely as s = In(City) and actions as Go(ConnectedCity). Identify why this abstraction fails for an EV, and write the corrected state formulation.
Show Answer
- Under-Abstraction: Retaining too much physical detail (e.g., modeling tire pressure, seat temperature, millisecond wind gusts in route planning). Result: The state space explodes exponentially into infinite or computationally intractable sizes, causing search algorithms to exhaust memory and time.
- Over-Abstraction: Discarding essential details required to ensure action validity in the physical world (e.g., omitting battery charge level for an electric vehicle, or omitting fuel constraints for an airplane). Result: The search algorithm finds an "optimal abstract solution" that physically fails or stalls halfway through execution in the real world.
Why the naive formulation fails: A standard gas vehicle can assume gas stations are plentiful and fill-up is rapid. An Electric Vehicle has limited battery capacity (e.g., 60 kWh), varying terrain energy consumption (uphill vs. downhill regenerative braking), and requires charging stations. If battery state is omitted from the state description, the agent may select a path between two cities with no charging stations that exceeds the vehicle's battery range, resulting in the car stranding.
Corrected Formal State Representation:
- State
s = (City, BatteryLevel_kWh)- Actions
{ Drive(City_next) : EnergyNeeded(City, City_next) ≤ BatteryLevel }, { Charge(Target_kWh) : if City has charging station }- Transition Model
RESULT((c, b), Drive(c′)) = (c′, b - EnergyNeeded(c, c′) + Regen(c, c′))- Goal Test
City == Destination ∧ BatteryLevel ≥ SafetyBuffer_kWh- Path Cost
- Weighted combination of travel time, charging time, and electricity cost ($).
When Reflex Fails: Reflex vs. Problem-Solving Agent Limits
(a) Can a Simple Reflex Agent solve the Two-Room Vacuum World if its sensors can only perceive the status of the current room (Clean/Dirty) but cannot perceive which room it is in (A or B)? Prove your answer.
(b) How does a Model-Based Agent or a Problem-Solving Agent overcome this sensory limitation?
Show Answer
Proof by Contradiction / Exhaustive Rule Enumeration:
If the agent only perceives [Clean] or [Dirty], there are only 2 possible percepts. A deterministic simple reflex agent has only 3² = 9 possible condition-action rule sets.
- When percept is
[Dirty], the rational reflex rule must beSuck. - When percept is
[Clean], what action should the agent take?- If rule is
if Clean then Left: When the agent cleans Room A, it perceives Clean and moves Left → bumps into the left wall → remains in Room A → perceives Clean → moves Left forever in an infinite loop. Room B is never cleaned! - If rule is
if Clean then Right: When the agent cleans Room B, it moves Right → bumps into the right wall → loops forever. Room A is never cleaned! - If rule is
if Clean then Suck: Agent does nothing and stays in the same room forever.
- If rule is
- Model-Based Reflex Agent: Maintains an internal state variable tracking its past actions. If it executed
Rightpreviously, it updates its internal state model to believeLocation = B. Even if its raw sensor only saysClean, its internal state model knows it is in Room B and has already cleaned Room A, allowing it to halt or take appropriate actions. - Problem-Solving / Search Agent: Uses belief state search (searching in the power set of physical states — the set of all possible worlds the agent might be in). It plans a single sequence of actions that works for every state in its belief state, e.g.
[Right, Suck, Left, Suck]: movingRightfirst puts the agent in Room B wherever it started (moving into a wall does nothing), so the rest of the plan cleans both rooms.[Suck, Right, Suck, Left, Suck]also works. A 3-step plan such as[Suck, Right, Suck]does not: if the agent starts in Room B,Rightleaves it in B and Room A is never cleaned.