Problem Solving — CS & DS

Lecture 24 — Graphs as Models

Learning objectives

Case-based lecture: you attempt, we discuss, then we reveal.

Today

The plan

Key definitions

Key definitions

Explain each in one breath; the cases will do the heavy lifting.
Worked example

The Friend Circle: adjacency list and BFS

cs-093

Students 1..6; friendships (1,2), (1,3), (4,5). How many separate friend circles, and how big is each?

from collections import deque

pairs = [(1, 2), (1, 3), (4, 5)]
adj = {}
for u, v in pairs:
    adj.setdefault(u, []).append(v)
    adj.setdefault(v, []).append(u)

visited = set()
sizes = []
for start in range(1, 7):
    if start in visited:
        continue
    frontier = deque([start])
    visited.add(start)
    size = 0
    while frontier:
        u = frontier.popleft()
        size += 1
        for w in adj.get(u, []):
            if w not in visited:
                visited.add(w)
                frontier.append(w)
    sizes.append(size)
print(len(sizes), sorted(sizes))

Expected: 3 circles of sizes 3, 2, 1

Cost: O(V + E) - each vertex enqueued once, each edge scanned twice (undirected).

Worked example

The Prerequisite Chain: topological order by peeling

cs-095

Courses a..e; prerequisites b<a, c<a, d<b, e<c. Order the courses so every prerequisite comes first.

deps = {"a": ["b", "c"], "b": ["d"], "c": ["e"], "d": [], "e": []}
indeg = {k: len(v) for k, v in deps.items()}
queue = [k for k, v in indeg.items() if v == 0]
order = []
while queue:
    c = queue.pop()
    order.append(c)
    for k, v in deps.items():
        if c in v:
            indeg[k] -= 1
            if indeg[k] == 0:
                queue.append(k)
print(sorted(order))

Expected: a valid order exists: a, b, c, d, e (e.g. d, e, c, b, a)

Cost: O(V + E) with a real reverse-adjacency map (the demo re-scans deps for teaching clarity - worth flagging as the O(V*E) version).

Worked example

The Epidemic Alarm: BFS measures time, not just reach

cs-096

Contacts spread infection per day: edges (1,2), (2,3), (2,4), (4,5). Infection starts at 1. On which day does each person fall ill?

from collections import deque

edges = [(1, 2), (2, 3), (2, 4), (4, 5)]
adj = {}
for u, v in edges:
    adj.setdefault(u, []).append(v)
    adj.setdefault(v, []).append(u)

dist = {1: 0}
q = deque([1])
while q:
    u = q.popleft()
    for w in adj.get(u, []):
        if w not in dist:
            dist[w] = dist[u] + 1
            q.append(w)
print([dist.get(p) for p in range(1, 6)])

Expected: infection days: person 1:0, 2:1, 3:2, 4:2, 5:3

Cost: O(V + E); the day count equals the BFS layer, computed with no extra work.

Case attempt · lecture 24
Case cs-093 · Beginner

The Friend Circle

Model friendships as a graph; find the size of someone's circle of direct and indirect friends. Modelling first, traversal second.

⏱ 5 minutes — attempt now

Pseudocode, flowchart or Python. State one assumption. Compare with your neighbour at minute 4.

Discussion

cs-093 — discuss

Instructor: the reveal, the reasoning section and common wrong turns are in the instructor distribution for cs-093 — not embedded in this deck.

Case attempt · lecture 24
Case cs-094 · Foundational

The Campus Walk

Fewest corridors between two rooms. Breadth-first search on a small grid/campus map; levels as distances.

⏱ 5 minutes — attempt now

Pseudocode, flowchart or Python. State one assumption. Compare with your neighbour at minute 4.

Discussion

cs-094 — discuss

Instructor: the reveal, the reasoning section and common wrong turns are in the instructor distribution for cs-094 — not embedded in this deck.

Case attempt · lecture 24
Case cs-095 · Intermediate

The Prerequisite Chain

Order courses so prerequisites come first (topological sort). Detect cycles as 'impossible semester plans'.

⏱ 5 minutes — attempt now

Pseudocode, flowchart or Python. State one assumption. Compare with your neighbour at minute 4.

Discussion

cs-095 — discuss

Instructor: the reveal, the reasoning section and common wrong turns are in the instructor distribution for cs-095 — not embedded in this deck.

Case attempt · lecture 24
Case cs-096 · Advanced

The Epidemic Alarm

Rumour spreads in a social graph each hour from a set of starters; when does everyone know it? Multi-source BFS as simulation; ties to Lecture 29.

⏱ 5 minutes — attempt now

Pseudocode, flowchart or Python. State one assumption. Compare with your neighbour at minute 4.

Discussion

cs-096 — discuss

Instructor: the reveal, the reasoning section and common wrong turns are in the instructor distribution for cs-096 — not embedded in this deck.

Case attempt · lecture 24
Case cs-136 · Advanced

The Timetable Collision

Four study groups — G1, G2, G3, G4 — must book presentation slots. Some pairs share members and cannot present in the same slot:

⏱ 5 minutes — attempt now

Pseudocode, flowchart or Python. State one assumption. Compare with your neighbour at minute 4.

Discussion

cs-136 — discuss

Instructor: the reveal, the reasoning section and common wrong turns are in the instructor distribution for cs-136 — not embedded in this deck.

Check yourself

Common misconceptions

Summary

Summary & exit question

Exit question (choose one, 60 seconds)

  1. What is a node in the campus model, and why?
  2. What does BFS level number mean?
  3. When is there no valid ordering in cs-095?
Expected answers (instructor): junctions/rooms — decisions and meetings happen there minimum number of steps from the source exactly when the prerequisite graph has a cycle
→ / space: next · ←: back · Home/End: jump · Ctrl+P → PDF