State spaces and problem formulation
状态空间与问题建模
Decide what a search state must remember, distinguish states from paths, and build a key-and-door problem with explicit rules.
state-spacesReturning to the same room can change the problem
You start in a hall. A side room contains a key; a locked door in the hall leads to the exit. The plan is simple: enter the side room, take the key, return to the hall, and unlock the door.
A search program that remembers only the room name may reject the return to the hall as a repeated state. It then misses the solution. The two visits are different for planning purposes: on the second visit, you have a key. The state should therefore contain both location and key possession.
A state is a description chosen to support decisions. It need not reproduce the whole physical world. The paint color of the hallway can be irrelevant, while a single bit recording key possession can be indispensable.
Specify the problem before selecting the search algorithm
A deterministic search problem specifies a state set , start state , available actions , transition function , goal test, and action cost . A plan is an action sequence that reaches a goal. Its cost is the sum of its action costs. CS188, State Spaces
For our example, use three locations and a Boolean key flag. Entering the key room automatically collects the key. Keeping it after unlocking is part of the stated model; a consumable key would require a different transition rule.
The product has six combinations, but only four are reachable under these rules. A search space can be defined by a generator rather than by an explicit list of every possible state. The generator must still produce all legal successors and no illegal ones.
A useful sufficiency test is: if two histories produce the same stored state, do they have the same available actions, goal status, and successor states and costs under every action? If not, the representation has discarded relevant information. With timed doors, remaining time may matter; with limited fuel, fuel may matter. Different tasks can require different state descriptions of the same room.
A search node is a record about a route to a state. It can store the parent node, action, depth, and accumulated cost . Several nodes can describe the same state reached by different paths. A state graph merges equivalent states; a search tree unfolds possible paths, potentially repeating a state many times. AIMA’s Problem and Node interfaces make this separation explicit. AIMA Python, fixed source revision
Write and test the transition rules first
The complete program below implements the model, executes a proposed plan, and enumerates reachable states. Enumeration is only a sanity check; this example does not claim to optimize a route. An illegal action raises an error rather than silently leaving the agent in place.
def successors(state):
place, has_key = state
if place == 'hall':
result = [('fetch', ('key room', True), 1)]
if has_key:
result.append(('leave', ('exit', True), 1))
return result
if place == 'key room':
return [('return', ('hall', has_key), 1)]
if place == 'exit':
return []
raise ValueError("unknown location")
def execute(start, actions):
state, cost, trace = start, 0, [start]
for action in actions:
choices = {a:(s,c) for a,s,c in successors(state)}
if action not in choices:
raise ValueError("action is not legal in this state")
state, step_cost = choices[action]
cost += step_cost
trace.append(state)
return state, cost, trace
start = ('hall', False)
end, cost, trace = execute(start, ['fetch','return','leave'])
assert end == ('exit', True) and cost == 3
assert trace[0][0] == trace[2][0] and trace[0] != trace[2]
seen, pending = {start}, [start]
while pending:
for _,state,_ in successors(pending.pop()):
if state not in seen:
seen.add(state)
pending.append(state)
assert seen == {('hall',False),('key room',True),('hall',True),('exit',True)}
assert execute(start, [])[1] == 0
try:
execute(start, ['leave'])
except ValueError:
pass
else:
raise AssertionError("locked door was ignored")
The solution visits the hall twice but never repeats the same location-and-key state. Its three actions cost three units. Try changing the final action to leave before collecting the key: the transition function rejects it.
If state components have possible values, their unrestricted product has combinations. With independent Boolean items and positions, this is . Constraints can reduce the reachable subset. The teaching enumerator visits each reachable state once; using hashable states and a finite adjacency representation, its expected work is and stored reachability information is . It still needs the model’s own storage.
A smaller state is useful only if it preserves the task
Removing irrelevant detail reduces search, but merging states with different futures can destroy solutions or produce impossible plans. Conversely, retaining the entire action history when only current key possession matters creates unnecessary distinctions and can prevent effective duplicate detection.
Duplicate detection also depends on the algorithm’s objective. Reaching a state once does not always mean its best route has been found. Breadth-first search can settle minimum edge counts under equal action costs; weighted search must track accumulated costs and improve routes when appropriate. State equivalence and route quality are separate questions.
This model assumes fully observed, deterministic rules. If a door opens only with some probability, use a stochastic transition model. If key possession is uncertain because observations are incomplete, a belief over possible states may be required. Those changes affect the mathematical problem, not just the size of a tuple.
Find the missing state variable
- Why is
hallalone an insufficient state? Answer: it merges visits with and without a key, although the legalleaveaction differs. - Are all six location-and-key pairs reachable? Answer: no. The reachable pairs are hall without a key, key room with a key, hall with a key, and exit with a key.
- If the objective is to finish before a deadline and actions have different durations, what may need to be added? Answer: elapsed or remaining time, unless another representation preserves the same decision-relevant timing information.
- Two routes reach the same valid state with costs 3 and 8. Should they be two different physical states? Answer: not merely because their past costs differ. Keep route cost in search bookkeeping; retain the cheaper route when the algorithm’s conditions justify doing so.
Modeling errors often look like search failures
A fast search over an incorrect state space gives an incorrect answer quickly. Before benchmarking algorithms, check a few transitions manually, verify the goal test, and construct a case that revisits a location with changed resources. Problem formulation connects classical planning, constraint systems, robotics, and game AI, even when the later solvers use very different machinery.
Make a prediction, then check
Legal actions in the same hall differ depending on key possession. How should it be modeled?
Learning objectives
- Design a state representation preserving actions, goal status, and successor information.
- Use a key puzzle to distinguish state graphs, path nodes, and reachable-state counts.
Prerequisites & connections
This article can be used as an entry point.
Explore related knowledge →References
- CS188 Textbook — State Spaces and Search Problems
UC Berkeley CS188 course contributors - AIMA Python — search algorithms (commit f104e03, 2026-06-30)
AIMA Python contributors · 2026
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: cited-source comparison, re-derivation and recalculation, bilingual argument comparison, and executed Python assertions; no independent human peer review.
- Enumerated the four reachable key-puzzle states, the three-step solution, and an illegal exit; distinguished six product combinations from the reachable subset.
- Checked state sufficiency, action rules, terminal behavior, revisits, and route costs; did not label the enumerator an optimal solver.
- Compared arguments, modeling assumptions, numbers, and exercise answers across languages; structural checks separately compare display formulas, code, references, and main sections. No independent human peer review.
Source locations checked:
- CS188 Textbook — State Spaces and Search Problems · §1.2–1.2.2: problem components, state-space size, and graph/tree distinction
- AIMA Python — search algorithms (commit f104e03, 2026-06-30) · Problem and Node classes, fixed commit f104e03fdc1582f014b3a4c93f1a9b7d2da70114
Related topics