Lawfare Academy

CS 201 — Data Structures, Algorithms and Systems · Weeks 12–14

Graphs, search and planning

Full teaching sequence and cumulative subject work

Preparation: study 4.1–4.2 and 4.5: graphs, trees and traversals in the complete on-site Levin text. Attempt the investigation, work at least four exercises of increasing difficulty in each assigned section, and compare the selected hints/solutions only after a written attempt. Then complete the algorithm reading and implement the unit laboratory. For each algorithm give a specification, trace, correctness argument and time/space analysis.

Weighted shortest paths: implementation, proof and complexity — primary material, constructed-response tasks, complete worked model and changed-case examination →

Reachability, shortest paths and weighted costs

Breadth-first search discovers vertices in nondecreasing number of edges from the start when all edges have equal cost. A visited set prevents a cycle from causing repeated exploration. Mark on enqueue so several parents do not schedule the same vertex repeatedly. A parent mapping can reconstruct a discovered path, while a distance mapping records its edge count.

A reachable set does not contain enough information to reconstruct every path. A BFS shortest-path guarantee concerns edge count, not arbitrary travel cost. Introducing weights changes the optimization problem and may require a different algorithm and assumptions about edge signs.

Worked problem

Graph edges are A→B, A→C, B→D, C→D and D→A. Trace BFS from A, enqueueing B before C, and reconstruct one shortest path to D.

Trace the complete reasoning
  1. Begin queue [A], seen {A}, distance[A]=0. Expanding A enqueues B and C with distance 1 and parent A.

  2. Expand B to discover D at distance 2 with parent B. Expanding C sees D already discovered and does not enqueue it again.

  3. D’s edge back to A does not repeat A. Following parents gives D←B←A, hence path A,B,D.

  4. A,C,D is another path with the same edge count. The chosen tie order does not make it uniquely optimal.

Independent transfer problem

Assign weights A→B=100, B→D=1, A→C=2, C→D=2. Does the earlier BFS parent path minimize cost?

Compare the transfer solution

No. A,B,D costs 101 while A,C,D costs 4, although both use two edges. BFS remains correct for minimum edge count but does not solve this weighted-cost objective. A suitable nonnegative-weight shortest-path algorithm can compare cumulative costs; the objective and weight assumptions must be documented.

Learning objectives

  • Explain and trace the mechanisms in graphs, search and planning.
  • Apply the method to the worked example and changed-condition exercise.
  • Identify assumptions, failure cases and the evidence needed to justify a result.

Study the mechanism

A graph models entities as vertices and relationships as edges. The interpretation of an edge determines the problem. A road can have a distance or travel time; a course prerequisite edge indicates dependency rather than physical proximity. Directed and undirected graphs answer different questions.

Breadth-first search explores a graph by increasing number of edges from a start vertex. With equal edge costs, its first discovered path to a vertex has minimum edge count. For unequal positive costs, minimum hops need not mean minimum distance; use a suitable weighted-search algorithm. Track visited states when enqueuing to prevent repeated expansion and cycles. The identity of a state must include all relevant information: location alone is insufficient if fuel or permissions change possible actions.

A heuristic estimates remaining cost. An optimistic admissible heuristic supports certain optimality arguments for A*, but implementation choices, reopening nodes and consistency assumptions matter. A plausible-looking estimate is not automatically admissible. Before adopting sophisticated search, construct a tiny counterexample and establish a baseline. A correct BFS on an unweighted graph is more useful than an improperly specified heuristic search.

Worked example

from collections import deque

def reachable(graph, start):
    seen = {start}
    queue = deque([start])
    while queue:
        node = queue.popleft()
        for neighbor in graph.get(node, []):
            if neighbor not in seen:
                seen.add(neighbor)
                queue.append(neighbor)
    return seen

assert reachable({"A": ["B"], "B": ["A", "C"]}, "A") == {"A", "B", "C"}

The initial state contains A in both seen and the queue. Expanding A discovers B. Expanding B ignores already-seen A and discovers C. C has no listed outgoing edges. The result includes A because a zero-edge path reaches the start. The function returns a reachable set, not actual paths or weighted distances; producing those requires additional parent or cost records.

Check your understanding

When does BFS provide minimum-cost paths?

  1. When every edge has the same nonnegative cost
  2. For arbitrary positive edge weights
  3. Whenever vertices have descriptive names
Answer and reasoning for every option

Correct: When every edge has the same nonnegative cost Equal costs make hop count proportional to total cost.

Reconsider: For arbitrary positive edge weights Unequal weights break the hop-count equivalence.

Reconsider: Whenever vertices have descriptive names Labels do not establish an optimality guarantee.

Transfer laboratory: A prerequisite cycle

Courses A requires B, B requires C and C requires A. Explain why a visited set in reachability does not establish a feasible study sequence.

Work through the full solution

A visited set prevents infinite graph traversal but does not make a cyclic prerequisite system schedulable. A topological ordering exists only for a directed acyclic graph. Track in-progress versus finished states in DFS, or use indegrees and detect unprocessed vertices in Kahn’s algorithm. The remedy is to correct a prerequisite edge or explicitly define co-requisites.

Evidence of understanding

Identify the directed cycle and propose a cycle-detection method rather than merely stopping traversal.

Complete on-site teaching readings

These are full attributed source sections, not previews. Read them alongside the original Academy explanation and code.

  1. 12 . Graphs · Pat Morin
  2. 12 . 1 AdjacencyMatrix: Representing a Graph by a Matrix · Pat Morin
  3. 12 . 2 AdjacencyLists: A Graph as a Collection of Lists · Pat Morin
  4. 12 . 3 Graph Traversal · Pat Morin
  5. 12 . 4 Discussion and Exercises · Pat Morin

Open in My Learning to record progress →