Graphs and Graph Traversal

Learn how programs represent graphs and search them. Store a graph as an adjacency list or an adjacency matrix and judge the cost of each. Trace and implement breadth-first and depth-first search in Python, then use them to find paths with the fewest edges, connected components and reachable vertices. Finish by detecting cycles and putting dependent tasks in a valid order with topological sort.

IntermediateLesson 8 of 10 in Data Structures and Algorithms Course

What you will learn

  1. Use the standard vocabulary of graphs, store a graph as an adjacency list or an adjacency matrix, and turn networks, grids and puzzles into graphs that a program can search.
    • Use the vocabulary of graphs
      Name the parts and kinds of graphs, count degrees and edges, and describe paths, cycles and connectivity precisely enough to reason about algorithms.
    • Store a graph as an adjacency list or an adjacency matrix
      Build both standard representations in Python, compare their memory use and the cost of common operations, and choose the right one for a sparse or a dense graph.
    • Model problems as graphs
      Decide what the vertices and edges are in networks, grids, dependencies and puzzles, choose directed or undirected edges, and search graphs that are generated on the fly instead of stored.
  2. Explore a graph layer by layer with a queue, and use breadth-first search to find paths with the fewest edges in unweighted graphs, grids and puzzles.
    • Run breadth-first search with a queue
      Carry out BFS step by step, mark vertices at the right moment, implement it in Python with a deque and explain why it runs in O(V + E) time.
    • Find shortest paths in unweighted graphs with BFS
      Record distances and parents during BFS, rebuild a path with the fewest edges, and apply the method to grids, puzzles and several starting points at once.
  3. Follow paths as deep as possible and backtrack, implement depth-first search recursively and with an explicit stack, use discovery and finishing times, and choose between BFS and DFS for a problem.
    • Run depth-first search recursively and with a stack
      Trace DFS by hand, write it recursively and iteratively in Python, avoid the stack-marking and recursion-depth pitfalls, and extend it to visit a whole graph.
    • Use discovery and finishing times
      Record when DFS discovers and finishes each vertex, read the nesting of these intervals, and classify every edge of a directed graph as a tree, back, forward or cross edge.
    • Choose between BFS and DFS
      Compare the two searches on visit order, paths, memory and typical uses, and pick the one that answers a given question.
  4. Use full traversals to split an undirected graph into connected components, and answer one-way reachability questions in directed graphs, including whether every vertex can reach every other.
    • Find the connected components of an undirected graph
      Label every vertex with its component by repeated searches, count components and answer connection queries, and apply the method to regions in a grid.
    • Answer reachability questions in directed graphs
      Find everything a vertex can reach, reverse a graph to find everything that can reach a vertex, and test whether a directed graph is strongly connected.
  5. Find cycles in undirected and directed graphs, and turn a directed acyclic graph of prerequisites into a valid order of tasks with depth-first search or with Kahn's algorithm.
    • Detect cycles in undirected and directed graphs
      Use DFS with a parent check in undirected graphs and with three vertex states in directed graphs, recover the cycle that was found, and avoid confusing two routes with a cycle.
    • Order tasks with a DFS topological sort
      Explain when a topological order exists, find one from DFS finishing times, and check any proposed order against the edges.
    • Order tasks with Kahn's algorithm
      Repeatedly remove tasks with no remaining prerequisites, use the result to detect a cycle, and compare this queue-based method with the DFS method.

Graph Traversal study guide

5 chapters

1

Describe graphs and store them in a program

Programs need a precise description of what their vertices and edges represent before a search can answer a useful question. Graph vocabulary distinguishes immediate neighbors from reachable vertices and separates one-way links from two-way links. Adjacency lists and matrices then turn those ideas into data. Grids and puzzles show how a neighbor function can describe a graph without storing every edge.

1.1 Vertices, edges, paths, and cycles

A graph describes objects and the links between them. Its vertices are the objects; its edges are the links. Writing G=(V,E) names the vertex set and edge set. In a cost such as O(V+E), the letters mean their counts.

Read the direction first

An undirected edge A–B works both ways. A directed edge A → B leaves A and enters B; it does not provide a route back. A friendship can be undirected, while "Ana follows Ben" describes a directed relation. Adjacent vertices are neighbors. An undirected vertex's degree counts incident edges. A directed vertex has an in-degree and an out-degree, counting incoming and outgoing edges separately.

Every undirected edge contributes to two degrees, so the handshake lemma gives a degree sum of 2E. Each directed edge contributes once to the total in-degree and once to the total out-degree; each total equals E.

Take the undirected edges A–B, A–C, B–D, C–D, C–E, D–F, E–F. There are 6 vertices and 7 edges. A, B, E, and F have degree 2; C and D have degree 3. The sum is 14. D's immediate neighbors are B, C, and F, even though all six vertices are reachable from D.

Distinguish a route from a cycle

A path is a sequence whose consecutive vertices share an edge, following arrows in a directed graph. A simple path repeats no vertex. Some books use "walk" for a sequence that may repeat vertices and reserve "path" for simple paths. The length counts edges: A–B–D–F has length 3, although it lists four vertices. The unweighted distance is the fewest edges on any route, or infinity when no route exists.

A cycle returns to its start without repeating another vertex or an edge. In a simple undirected graph it needs at least three vertices. A–B–D–C–A and C–D–F–E–C are cycles in this example. Traversing A–B and immediately returning on the same edge is not one. Directed cycles follow arrows: two opposite arrows form a length-2 cycle, and a self-loop forms a length-1 cycle. A graph without cycles is acyclic; a directed acyclic graph is a DAG.

Describe the whole graph

A graph is simple when it has neither self-loops nor parallel edges. With n vertices, a simple undirected graph has at most n(n−1)/2 edges, and a simple directed graph at most n(n−1). For 10 vertices those bounds are 45 and 90. Thus a simple graph has O(V2) edges. Sparse graphs have far fewer edges than this maximum; dense graphs approach it. This distinction matters when choosing storage.

A vertex is reachable from another when a path leads to it. An undirected graph is connected when every pair has a path; its largest connected pieces are its connected components. A tree is connected and acyclic, with n−1 edges for n vertices. The six-vertex example has seven edges, exceeding the five a tree would have.

A weighted graph also stores a cost on each edge. Ordinary BFS and DFS follow adjacency without comparing those costs. Counting links and minimizing total cost are different questions.

Key Takeaways

  • A directed edge provides travel only in its arrow direction.
  • Degree counts incident edges; unweighted distance counts edges on a shortest path.
  • Undirected degrees total 2E; in-degrees and out-degrees each total E.
  • A simple graph has no self-loops or parallel edges.
  • A tree is a connected, acyclic undirected graph.

1.2 Adjacency lists and matrices

A search repeatedly asks for a vertex's neighbors. The way a graph stores those neighbors controls both its memory use and its running time. Keep every vertex in the representation, including vertices with no edges.

Build the two representations

An adjacency list stores each vertex's outgoing neighbors. With numbered vertices, use a list of lists. This builds the directed graph 0 → 1, 0 → 2, 1 → 2, 2 → 3, 3 → 1:

n = 4
edges = [(0, 1), (0, 2), (1, 2), (2, 3), (3, 1)]
adj = [[] for _ in range(n)]
for u, v in edges:
    adj[u].append(v)

The lists are [1, 2], [2], [3], and [1]. For an undirected edge also run adj[v].append(u). Named vertices can use a dictionary of lists. Initialize every key first so an isolated vertex has [].

An adjacency matrix stores a cell for every ordered vertex pair:

M = [[0] * n for _ in range(n)]
for u, v in edges:
    M[u][v] = 1

Its rows are 0 1 1 0, 0 0 1 0, 0 0 0 1, and 0 1 0 0. Row sums give out-degrees 2, 1, 1, 1; column sums give in-degrees 0, 2, 2, 1. Both totals are 5. An undirected matrix is symmetric; also set M[v][u] = 1. A simple graph has a zero diagonal.

Match storage to operations
OperationList of neighborsMatrix
StorageΘ(V+E)Θ(V2)
Test u → vO(deg⁡(u))O(1)
Enumerate u's neighborsO(deg⁡(u))O(V)
Add an edgeAmortized O(1)O(1)
Remove u → vO(deg⁡(u))O(1)
Full BFS or DFSO(V+E)O(V2)

Here degree means out-degree for a digraph. A list must scan to test membership or find an item to remove. A matrix has direct access to one cell, but listing neighbors still scans an entire row. The insertion costs assume the vertex set is already allocated and insertion does not first check for duplicates.

For an undirected network with 1,000,000 intersections and 3,000,000 road segments, lists need 1,000,000 list headers plus 6,000,000 neighbor entries. The matrix needs 1012 cells: even one bit per cell totals 125 GB. In 64-bit CPython, a list-of-lists matrix for 10,000 vertices has 108 references, about 800 MB before row overhead. A Python integer matrix is not a packed bit matrix.

Choose and index carefully

Lists suit sparse graphs and traversal. Matrices suit dense graphs or small graphs with many edge-existence queries. A dictionary of sets also uses Θ(V+E) space and offers average O(1) membership tests through hashing. Sets have no sorted order; sorting neighbors for a prescribed trace adds work.

Map named vertices to numeric matrix indices, for example index = {"A": 0, "B": 1}. For input labeled 1 through n, either subtract 1 everywhere or allocate n + 1 slots and leave slot 0 unused. Mixing the two conventions can silently connect the wrong vertices.

Key Takeaways

  • Store an undirected edge at both endpoints.
  • Include an empty neighbor list for every isolated vertex.
  • Lists use Θ(V+E) space; matrices use Θ(V2).
  • A matrix gives constant-time edge checks but scans a full row for neighbors.
  • Hash sets give average constant-time membership without a sorted neighbor order.
  • Use one consistent mapping from vertex labels to indices.

1.3 Networks, grids, and state spaces

Before choosing a search, decide what one vertex means and what one edge allows. A graph model must preserve the moves and constraints of the problem. The search can only answer questions about the model it receives.

Turn the question into a graph question

For a communication network, vertices might be devices and edges direct links. "Can X contact Y?" asks about reachability. "How many links must a message cross?" asks for an unweighted distance. "Which devices form separate groups?" asks for connected components. For dependent tasks, "What can run first?" asks for a topological order, and "Are the requirements circular?" asks about cycles.

Choose direction from the relation. Two-way roads and cable links are undirected. One-way streets, web links, and "task u must finish before task v" are directed. Converting a one-way street to an undirected edge creates a return route the actual network may not allow.

Generate grid neighbors safely

Treat an open grid cell (r, c) as a vertex. The 4-neighborhood permits up, down, left, and right. The 8-neighborhood also permits four diagonal moves. A wall is not a vertex the search may enter.

def neighbors(grid, r, c):
    rows, cols = len(grid), len(grid[0])
    for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
        nr, nc = r + dr, c + dc
        if 0 <= nr < rows and 0 <= nc < cols:
            if grid[nr][nc] != "#":
                yield (nr, nc)

This function uses a nonempty rectangular grid. Check bounds before reading the cell. In Python, grid[-1] accesses the last row, so a missing lower-bound check can make the top connect to the bottom without raising an exception.

For a fully open grid with R rows and C columns, there are RC vertices. Horizontal edges number R(C−1) and vertical edges number C(R−1). A 4 × 5 grid therefore has 20 vertices and 31 undirected edges. These counts use four-way movement; adding diagonals changes the graph.

Search without storing every edge

An implicit graph supplies a neighbor function instead of a complete adjacency table. BFS and DFS can call that function whenever they process a vertex. A grid already records walls and open cells, so storing a second copy of every permitted move usually adds no useful information.

A state-space graph uses a complete system state as a vertex and one legal move as an edge. Consider four lock dials, each showing 0–9. One move turns one dial up or down one step, wrapping between 9 and 0. There are 10,000 states, each with eight neighbors, and therefore 40,000 undirected edges. From "0000", reaching "0202" takes four moves; reaching "0909" takes two downward turns.

The state must contain everything needed to decide the next legal moves. Store a visited state once so different move sequences do not trigger repeated searches of the same position. Estimate the possible states before starting: extra puzzle pieces can multiply the state count, and an implicit representation still needs memory for visited states.

Key Takeaways

  • Define vertices and legal moves before selecting a search.
  • Choose directed edges whenever the relation is one-way.
  • Four-way and eight-way grid movement produce different graphs.
  • Check grid bounds before indexing.
  • An implicit graph generates neighbors on demand.
2

Search a graph with breadth-first search

A breadth-first search expands from a source one distance layer at a time. Its queue and discovery rule explain both the order of exploration and the fewest-edge guarantee. Following a concrete queue trace makes the Python implementation easier to read. Distances and parent pointers then turn the same search into a route finder, including searches through grids or from several starting points.

2.1 The BFS queue and discovery rule

Breadth-first search, or BFS, explores a graph in layers. It begins with a source, then reaches its neighbors, then vertices two edges away, and continues outward. A first-in, first-out queue preserves that order.

Mark before adding to the queue

Mark the source and enqueue it. Remove a vertex from the front, inspect its neighbors, and mark and enqueue each undiscovered neighbor. Marking happens at discovery, before another vertex can enqueue the same neighbor.

from collections import deque

def bfs(adj, source):
    seen = {source}
    queue = deque([source])
    order = []
    while queue:
        u = queue.popleft()
        order.append(u)
        for v in adj[u]:
            if v not in seen:
                seen.add(v)
                queue.append(v)
    return order

adj includes every vertex, and its lists contain outgoing neighbors in a digraph. deque.append and deque.popleft take constant time. Using a list's pop(0) shifts the remaining items; on a wide frontier, repeated shifts can make the search quadratic.

Follow the queue step by step

Use undirected edges A–B, A–C, B–D, C–D, C–E, D–F, E–F. Start at A and examine neighbors alphabetically. The queue below runs from front to back.

RemovedNewly discoveredQueue afterward
AB, CB, C
BDC, D
CED, E
DFE, F
ENoneF
FNoneEmpty

When C examines D, D is already marked even though it has not been removed yet. When E examines F, F is already marked too. The visit order is A, B, C, D, E, F.

If marking waits until removal, B and C can both enqueue D, and D and E can both enqueue F. This trace produces seven additions after the initial source instead of five. Skipping duplicate removals can prevent repeated processing, but it does not prevent the extra entries. Without any visited check, cycles allow repeated visits indefinitely.

Account for every operation

With adjacency lists, each reached vertex enters and leaves the queue once. Each reached vertex's neighbor list is scanned once. The total number of entries is E in a digraph and 2E in an undirected graph, giving O(V+E) time for a full traversal. A matrix instead scans V cells per processed vertex and gives O(V2) worst-case time.

The queue and visited set need O(V) extra space. A star shows why the queue may be large: processing its center can enqueue all 1,000 leaves together. BFS does not always keep a small queue just because the paths are short.

A search from one source reaches exactly the vertices reachable from it. Other components stay unvisited, as do vertices blocked by arrow direction. Changing neighbor order may change the order within a layer, but it cannot change a vertex's distance layer or whether that vertex is reachable.

Key Takeaways

  • BFS processes vertices with a first-in, first-out queue.
  • Mark a vertex when it is enqueued to prevent duplicate queue entries.
  • Use deque.popleft() for constant-time removal from the front.
  • Adjacency-list BFS takes O(V+E) time and O(V) extra space.

2.2 Shortest paths and several starting points

BFS does more than find reachable vertices. Its layers give the fewest edges from the source. Record a distance and a parent at first discovery to obtain both the length and one actual shortest path.

Store distances and parents
from collections import deque

def shortest_paths(adj, source):
    dist = {source: 0}
    parent = {source: None}
    queue = deque([source])
    while queue:
        u = queue.popleft()
        for v in adj[u]:
            if v not in dist:
                dist[v] = dist[u] + 1
                parent[v] = u
                queue.append(v)
    return dist, parent

def path_to(parent, target):
    if target not in parent:
        return None
    path = []
    while target is not None:
        path.append(target)
        target = parent[target]
    return path[::-1]

Vertex labels here are not None, which marks the root's missing parent. Membership in dist also serves as the visited test. A missing vertex has no path from the source; its mathematical distance is infinity.

For edges A–B, A–C, B–D, C–D, C–E, D–F, E–F, alphabetical BFS from A gives distances A 0, B 1, C 1, D 2, E 2, F 3. Its parents are B ← A, C ← A, D ← B, E ← C, F ← D. Following parents from F gives F, D, B, A; reversing gives A, B, D, F. Another neighbor order may choose A, C, D, F, also three edges long.

Why first discovery is enough

The queue holds vertices in nondecreasing distance order. At any instant its distance values are at most two consecutive layers. Before a vertex at distance d + 1 is processed, every vertex at distance d has been processed. If a shorter route to a newly discovered vertex existed, its previous vertex would have been processed earlier and would already have discovered it.

Check traces using edges. In an undirected graph, neighboring distances differ by at most 1. In a digraph, an edge u → v from a reached u satisfies dist[v] <= dist[u] + 1; the reverse inequality need not hold.

In the maze with rows ...#, ##.#, ...., .##., four-way BFS finds a route from (0, 0) to (3, 3) through (0, 1), (0, 2), (1, 2), (2, 2), and (2, 3). Seven cells mean six moves. The grid neighbor function replaces the adjacency list without changing the BFS rule.

Start from several sources

For multi-source BFS, initialize every distinct source with distance 0 and place them all in the queue before the loop. The result is each vertex's fewest-edge distance from the nearest source, in one O(V+E) pass. For distances to exits in a directed corridor graph, reverse every edge and start at all exits. Undirected corridors need no reversal.

BFS minimizes edge count. If A–B costs 10 and A–C and C–B cost 1 each, BFS chooses one edge costing 10 although two edges cost 2. Equal nonnegative edge costs make fewest-edge paths cheapest too. With unequal weights, the edge-count guarantee alone cannot settle total cost. DFS also lacks the fewest-edge guarantee: alphabetical DFS reaches F along A–B–D–C–E–F, with five edges, although BFS needs three.

Key Takeaways

  • Assign distance and parent at first discovery.
  • Reverse the parent chain to reconstruct a source-to-target path.
  • BFS finds one shortest unweighted path; ties depend on neighbor order.
  • Count moves as edges, one fewer than cells on a simple grid route.
  • Multi-source BFS measures distance from the nearest source.
  • Reverse directed edges to find distances to the nearest exit.
3

Explore a graph with depth-first search

A depth-first search commits to one route, then returns to explore the alternatives it left behind. Recursive calls and explicit stacks provide two ways to manage that work, with different memory details. Entry and exit times expose the structure of the search tree and distinguish directed edge types. Comparing this structure with BFS layers helps you choose the search that produces the information a problem needs.

3.1 Recursive DFS and explicit stacks

Depth-first search, or DFS, follows one route until it cannot discover another vertex, then backtracks. Recursion naturally remembers where each active call paused. An explicit stack can hold pending work instead.

Enter, explore, finish
def full_dfs(adj):
    seen, parent, postorder = set(), {}, []
    def visit(u):
        seen.add(u)
        for v in adj[u]:
            if v not in seen:
                parent[v] = u
                visit(v)
        postorder.append(u)
    for s in adj:
        if s not in seen:
            parent[s] = None
            visit(s)
    return parent, postorder

A vertex is discovered on entry and finishes after its neighbor loop. The outer loop makes this a full DFS: each unvisited start grows another tree, and the collection is a DFS forest. Keep the same visited set across all starts.

On the undirected graph A–B, A–C, B–D, C–D, C–E, D–F, E–F, alphabetical DFS from A discovers A, B, D, C, E, F. At D, B is already visited, so C is next. At C, A and D are visited, so E is next. F has no new neighbor and finishes. The returns then finish E, C, D, B, A. Parent pointers record A–B–D–C–E–F, a five-edge route to F, although a three-edge route exists.

Replace recursive calls with pending entries
def dfs_stack(adj, source):
    seen, parent, order = set(), {}, []
    stack = [(source, None)]
    while stack:
        u, p = stack.pop()
        if u in seen:
            continue
        seen.add(u)
        parent[u] = p
        order.append(u)
        for v in reversed(adj[u]):
            if v not in seen:
                stack.append((v, u))
    return order, parent

The stack is last-in, first-out. Reversing each list makes the first listed neighbor pop first, reproducing recursive discovery order. With the example's lists pushed in their original order, the visit order becomes A, C, E, F, D, B.

In this push-all-neighbors version, mark at pop time and assign the parent then. On triangle A–B, A–C, B–C, marking both B and C when pushing from A would give them both parent A. A depth-first tree instead reaches one through the other. Multiple pending entries for a vertex are allowed; after its first pop, later copies are skipped. This code records discovery, not recursive finishing events.

Choose the right memory model

Both implementations scan each visited vertex's list once, taking O(V+E) time; full matrix traversal takes O(V2). Recursive DFS uses O(V) extra space for visited vertices and active calls. A long path can make the call depth V. CPython commonly starts with a 1,000-call recursion limit; sys.getrecursionlimit() reports the current value. A 10,000-vertex path exceeds that default.

The push-all stack may hold O(E) pending entries, including duplicates, so its extra space is O(V+E). To retain the recursive O(V) bound without recursion, store one frame per active vertex, such as (u, iter(adj[u])), and advance one neighbor at a time. Finishing occurs when that frame's iterator is exhausted. This frame version also preserves entry and exit events for later DFS applications.

Key Takeaways

  • DFS finishes a vertex after exploring its neighbors.
  • Full DFS shares one visited set across all starts.
  • The push-all stack version marks and records parents at first pop.
  • Recursive DFS needs O(V) extra space; the push-all stack can need O(V+E).
  • Iterator frames reproduce recursion without using Python call depth.

3.2 DFS times and edge types

DFS has two important events for each vertex: discovery and finish. Recording both reveals the nesting of search paths. It also distinguishes a return to an active ancestor from an edge to a branch that has already finished.

Keep one clock for the whole forest

Advance a shared clock on entry and again on exit. Write d[u] for discovery and f[u] for finish. Every vertex has d[u] < f[u]; a full traversal of V vertices uses times 1 through 2V. Discovery order is preorder; finishing order is postorder.

def dfs_times(adj):
    color = {u: "white" for u in adj}
    d, f, parent = {}, {}, {}
    clock = 0
    def visit(u):
        nonlocal clock
        color[u] = "gray"
        clock += 1
        d[u] = clock
        for v in adj[u]:
            if color[v] == "white":
                parent[v] = u
                visit(v)
        color[u] = "black"
        clock += 1
        f[u] = clock
    for u in adj:
        if color[u] == "white":
            parent[u] = None
            visit(u)
    return d, f, parent

White means undiscovered, gray means active, and black means finished. The gray vertices form the current recursive path. A pending entry in a push-all stack is not enough to make a vertex gray; gray specifically describes an entered, unfinished call or iterator frame.

Read nested intervals

Consider the digraph A → B, A → C, B → C, C → A, D → C. Search vertices and neighbors alphabetically. A enters at 1, B at 2, C at 3. C sees active A, then finishes at 4; B finishes at 5 and A at 6. D enters at 7, sees finished C, and finishes at 8.

VertexDiscoveryFinish
A16
B25
C34
D78

The intervals of B and C lie inside A's interval, matching their descent from A. D's interval is disjoint. DFS intervals are always nested or disjoint; partial overlap cannot occur because a child call finishes before its parent resumes.

Classify directed edges when examined
State of target v on u → vEdge typeMeaning
WhiteTreeDiscovers v
GrayBackReturns to the active path
Black, d[u] < d[v]ForwardReaches a finished descendant
Black, d[u] > d[v]CrossReaches an earlier branch or tree

Thus A → B and B → C are tree edges, C → A is back, A → C is forward, and D → C is cross. The edge A → C is examined only after B's recursive call returns; C has already finished then. A visited flag alone cannot distinguish these cases.

In an undirected DFS, edges are tree or back edges. The reverse adjacency entry for a child's parent refers to the original tree edge and is excluded when looking for cycles.

Changing neighbor order can change the edge types. If A explores C before B, A → C becomes a tree edge and B → C becomes cross. The existence of at least one back edge remains equivalent to a directed cycle. In a DAG there are no back edges, which makes decreasing finishing time useful for ordering dependencies.

Key Takeaways

  • DFS assigns one discovery and one finishing time per vertex.
  • Gray vertices are exactly the active recursive path.
  • DFS time intervals are nested or disjoint.
  • White targets give tree edges; gray targets give back edges.
  • Black targets give forward or cross edges according to ancestry.
  • The presence of a directed back edge proves a directed cycle.

3.3 Choosing a search for the question

BFS and DFS both discover the vertices reachable from a source. Their different exploration orders produce different paths and different useful information. Start by deciding what the result must guarantee.

Match the result to the method
NeedSuitable searchReason
Decide whether a route existsBFS or DFSBoth explore the reachable set
Fewest edges or equal-cost movesBFSLayers increase by one edge
Undirected connected componentsBFS or DFSEach start reaches one whole component
Discovery and finishing structureDFSCalls have nested lifetimes
Directed cycle detectionDFS with active statesAn edge to gray closes an active path
Dependency orderDFS on a DAG, or Kahn's algorithmBoth respect prerequisite arrows

A target may be found early. BFS can stop when it first discovers the target and still guarantee the fewest edges. DFS can stop when it reaches the target and return a route, but that route need not be shortest. A reachability-only task does not require distances or finishing times.

For the graph A–B, A–C, B–D, C–D, C–E, D–F, E–F, alphabetical BFS discovers A, B, C, D, E, F and reaches F through A–B–D–F. Alphabetical DFS discovers A, B, D, C, E, F and reaches F through A–B–D–C–E–F. Both find the same six vertices. Only BFS's parent path has the three-edge shortest-path guarantee.

Compare the memory shapes

BFS stores a frontier of discovered vertices waiting to be processed. In a tree where every non-leaf vertex has ten children, the layer at depth 6 contains 1,000,000 vertices. BFS can hold that entire layer. Recursive DFS follows one path at a time; a path to that depth needs only seven active calls, counting the root at depth 0. The visited set still grows with the total discovered vertices.

On a long chain the tradeoff changes: the BFS queue stays small, while recursive DFS can require V active calls and exceed Python's recursion limit. An iterator-frame DFS moves those calls to an explicit stack. The simpler push-all-neighbors DFS can hold many pending neighbors and duplicates, so it does not have the same path-only stack bound.

Compare actual work

With adjacency lists, full BFS and DFS both take O(V+E) time. Each visits vertices once and examines each adjacency list once. With a matrix, full traversal takes O(V2). Replacing recursion with a queue does not by itself change the asymptotic amount of edge work.

Neighbor order also matters when interpreting a trace. Different orders can change a chosen parent, a DFS tree, or the order within a BFS layer. They do not change the reachable set or the unweighted distances. A fixed alphabetical trace assumes the lists are already in that order; sorting them during the search has an additional cost.

Depth-first backtracking can also try alternative paths in puzzles or enumerate simple paths. Enumerating all simple paths is a larger task than ordinary DFS with one permanent visited set: a graph can have very many paths even though one traversal is linear. Choose a traversal for the information it must produce, then account for any extra work that information requires.

Key Takeaways

  • Both searches answer reachability and undirected component questions.
  • Use BFS for a fewest-edge guarantee.
  • Use DFS entry and exit structure for times, cycles, and DFS topological sorting.
  • BFS frontiers can be wide; recursive DFS paths can be deep.
4

Solve connectivity and reachability problems

Connectivity questions ask which vertices belong together and which routes actually exist. In an undirected graph, repeated searches divide the vertices into connected components that can answer many later queries. Arrow direction changes the meaning of the question: a route out does not guarantee a route back. Reversing a digraph gives a direct way to study incoming routes and test strong connectivity.

4.1 Connected components and flood fill

An undirected graph may contain several separate networks. A connected component is a largest group in which every pair of vertices has a path. Components partition the vertices: no vertex belongs to two components, and an isolated vertex forms a component by itself.

Label each component once

Scan the complete vertex collection. When a vertex has no label, start a search from it and assign one new component number to everything reached. Reuse the labels so later starts skip vertices already handled.

def components(adj):
    label = {}
    count = 0
    for source in adj:
        if source in label:
            continue
        label[source] = count
        stack = [source]
        while stack:
            u = stack.pop()
            for v in adj[u]:
                if v not in label:
                    label[v] = count
                    stack.append(v)
        count += 1
    return label, count

This stack search marks at push time because it only needs component membership, not a DFS tree or finishing structure. A queue would work too.

For vertices 0–8 and edges 0–1, 1–2, 3–4, 5–6, 6–7, 5–7, numeric scanning gives labels 0 for {0, 1, 2}, 1 for {3, 4}, 2 for {5, 6, 7}, and 3 for {8}. Four searches produce four components. Starting again from 1 would count the first group twice; omitting vertex 8 from the input would lose a component.

After labeling, the query "Are u and v connected?" takes constant time: compare label[u] and label[v]. Vertices 0 and 2 match; 4 and 5 do not. Preprocessing costs O(V+E) overall, not that amount per component: each vertex receives a label once and each adjacency entry is examined once.

Check the result with edges

A graph with V vertices and c components has at least V−c edges. Each component with k vertices needs at least k − 1 edges to connect them; adding across components gives the bound. Equality means every component is a tree, so the graph is a forest. More edges mean at least one cycle.

The example has V = 9, c = 4, and E = 6. A forest with that component count would have five edges; the sixth edge closes triangle 5–6–7. To test whether a nonempty graph is a tree, check that one search reaches all vertices and that it has exactly V − 1 edges. The edge count alone cannot establish connectedness.

Count grid regions

Flood fill is a search of one connected grid region, such as the cells recolored by a paint-bucket tool. For the land map with rows 11000, 10011, 00100, 00011, count only land cells and use a fixed neighbor rule.

With four-way movement the regions are {(0, 0), (0, 1), (1, 0)}, {(1, 3), (1, 4)}, {(2, 2)}, and {(3, 3), (3, 4)}: four islands. With eight-way movement, (2, 2) joins diagonally to both (1, 3) and (3, 3), giving two islands. A change in neighbor rules changes connectivity even when the stored grid is identical.

Build undirected adjacency in both directions before labeling. If 0–1 is stored only as 1 → 0, a search starting at 0 misses 1 and can split a real component incorrectly.

Key Takeaways

  • Keep one label per vertex and start searches only from unlabeled vertices.
  • An isolated vertex counts as a component.
  • Component labels answer later connectivity queries in O(1) time.
  • A forest has exactly V−c edges.
  • Flood-fill regions depend on the permitted grid neighbors.

4.2 Reachability along arrows and reversed arrows

Directed reachability is one-way. A search from s follows outgoing edges and returns the vertices that s can reach. To answer a question about routes into a target, reverse the arrows first.

Separate three connectivity questions
QuestionMeaning
What is reachable from s?Search outgoing edges from s
Is the digraph weakly connected?Ignore directions and test undirected connectivity
Is the digraph strongly connected?Every vertex can reach every other vertex

Consider A → B, B → C, C → A, C → D. A reaches all four vertices, but D cannot leave itself. The graph is weakly connected and is not strongly connected. A, B, and C can each reach the other two through their cycle.

A full DFS beginning at A builds one tree containing all four vertices. That does not make them a strongly connected component. Directed DFS trees depend on where the outer loop starts; undirected component membership does not.

Build and search the reverse graph

The reverse graph has the same vertices and each arrow flipped. A route u → … → t becomes t → … → u. Searching from t in the reverse graph therefore finds exactly the vertices that can reach t in the original.

def reverse_graph(adj):
    rev = {u: [] for u in adj}
    for u in adj:
        for v in adj[u]:
            rev[v].append(u)
    return rev

def reached(adj, source):
    seen = {source}
    stack = [source]
    while stack:
        u = stack.pop()
        for v in adj[u]:
            if v not in seen:
                seen.add(v)
                stack.append(v)
    return seen

The reverse of the example has B → A, C → B, A → C, D → C. From A, reverse search reaches A, C, B but misses D. This identifies D as unable to reach A in the original. Building the reverse takes O(V+E) time and space, including empty lists for vertices without incoming edges.

Test strong connectivity with two searches

For a nonempty digraph, choose any s. Search from s in the original and the reverse. The graph is strongly connected exactly when both searches reach every vertex.

The original search shows that s reaches any v. The reverse search shows that any u reaches s in the original. Combining the two paths gives u → … → s → … → v. If a search misses a vertex, at least one of these required directions is absent. Two searches and reversal still take O(V+E) time.

This also guides practical dependency questions. If u → v means "u must finish before v," searching from X finds tasks downstream of X. Searching from X in the reverse finds its direct and indirect prerequisites. Exclude X itself when reporting other tasks: the search includes its start even when it has no incident edges.

For one-way corridors, distances to several exits require multi-source BFS from those exits in the reverse graph. Starting at exits in the original graph instead measures how far the exits can reach, which answers a different question.

Key Takeaways

  • Forward search finds vertices reachable from its start.
  • Reverse search from a target finds vertices that can reach it.
  • Weak connectivity ignores arrows; strong connectivity requires routes both ways.
  • A nonempty digraph is strongly connected when both searches from one vertex reach all vertices.
5

Detect cycles and order dependencies

Cycles and dependencies connect traversal to scheduling. An undirected return edge needs a different test from a directed edge into the active search path. Once a dependency graph is known to be acyclic, DFS finishing times or a queue of ready tasks can produce a valid order. Tracing both methods shows why their answers may differ and how a stalled schedule exposes a circular requirement.

5.1 Cycle tests that match the graph

A cycle in a dependency graph makes a complete schedule impossible. In an undirected network, a cycle provides a redundant route. DFS can detect both, but the correct test depends on whether the edges have directions.

Exclude the parent in a simple undirected graph

When DFS reaches u through p, the neighbor p is already visited because the same undirected edge is stored at both ends. Ignore that return entry. Any other visited neighbor reveals a cycle.

On triangle A–B, B–C, A–C, DFS follows A to B to C. C sees A visited, and A is not C's parent B. The tree route A–B–C plus C–A closes a cycle. A single edge A–B does not form a cycle merely because B's list also contains A. This parent-only check applies to simple undirected graphs; parallel edges need edge identities to distinguish the edge used to enter a vertex.

For a counting check, an undirected graph with c components has a cycle exactly when E>V−c. If connected, this becomes E≥V. The six-vertex, seven-edge running example therefore contains a cycle. Counting detects existence; it does not reconstruct the route.

Track the active path in a digraph

"Visited and not the parent" is wrong for directed graphs. In the diamond A → B, A → C, B → D, C → D, DFS can finish D through B before C later examines C → D. D is visited, yet no arrow route returns to C.

Use white, gray, and black states instead. Only an edge to gray closes a directed cycle, because gray vertices are the current active path.

def has_directed_cycle(adj):
    color = {u: "white" for u in adj}
    def visit(u):
        color[u] = "gray"
        for v in adj[u]:
            if color[v] == "gray":
                return True
            if color[v] == "white" and visit(v):
                return True
        color[u] = "black"
        return False
    for u in adj:
        if color[u] == "white" and visit(u):
            return True
    return False

The full outer loop matters: a cycle may lie outside the first start's reachable set. A set on_path, updated on entry and exit, can represent gray beside a permanent visited set. Never leave finished vertices in on_path, or the diamond can be mistaken for a cycle. The total time with adjacency lists is O(V+E).

Recover the cycle and handle small cases

For A → B, B → C, C → A, C → D, DFS makes A, B, C gray. C → A finds gray A. If parents record B ← A and C ← B, follow them from C back to A, reverse C, B, A into A, B, C, and append A to close the route. The reported cycle is A → B → C → A.

A self-loop u → u finds gray u immediately. Opposite directed edges u → v and v → u also form a cycle; the undirected parent exclusion must not suppress the return arrow. An edge to a black vertex is safe by itself because its earlier exploration has ended. Kahn's algorithm offers another directed-cycle test: failure to output every vertex proves a cycle remains.

Key Takeaways

  • In a simple undirected DFS, ignore the current vertex’s parent edge.
  • In a digraph, a visited target alone does not prove a cycle.
  • A directed edge to gray closes the active path into a cycle.
  • Search all unvisited starts to detect cycles anywhere.
  • Parent pointers reconstruct the cycle found by a back edge.
  • Directed self-loops and pairs of opposite arrows are cycles.

5.2 Dependency orders from DFS finishes

A topological order lists every vertex so each arrow points from an earlier position to a later one. Write an edge u → v when u must happen before v. The order answers a dependency question, not a question about alphabetical order or shortest routes.

Establish whether an order can exist

A digraph has a topological order exactly when it is a DAG. A cycle would require each task to precede the next all the way back to itself. In a nonempty DAG, at least one vertex has in-degree zero: following incoming edges forever in a finite graph would otherwise repeat a vertex and create a cycle. Remove a zero-in-degree vertex and the remaining graph is still a DAG, so all vertices can be ordered.

Use the course prerequisites P → D, M → D, D → A, M → A, D → B, A → L, S → L. P is Programming, M Discrete Math, S Statistics, D Data Structures, A Algorithms, B Databases, and L Machine Learning.

Append on finish, then reverse
def topological_dfs(adj):
    color = {u: "white" for u in adj}
    finished = []
    def visit(u):
        color[u] = "gray"
        for v in adj[u]:
            if color[v] == "gray":
                raise ValueError("Directed cycle")
            if color[v] == "white":
                visit(v)
        color[u] = "black"
        finished.append(u)
    for u in adj:
        if color[u] == "white":
            visit(u)
    return finished[::-1]

For every edge u → v in a DAG, v finishes before u. If v is white, its recursive call completes before u. If v is black, it has already finished. It cannot be gray because that would be a back edge and a cycle. Reversing finishes therefore puts u before v. The full search takes O(V+E) time and O(V) extra space.

Search the course vertices alphabetically: A, B, D, L, M, P, S, with alphabetical neighbors. Starting at A finishes L then A. B finishes next. D finds its successors finished and then finishes; M, P, S follow. The finishing list is L, A, B, D, M, P, S. Reverse it to S, P, M, D, B, A, L.

Check the schedule independently

Record each vertex's position and check pos[u] < pos[v] for every edge. The course order puts P and M before D, D and M before A, D before B, and A and S before L. All seven requirements hold. Also check that every vertex appears once: satisfying edge inequalities alone would not catch an omitted isolated vertex.

Discovery order is not a substitute for reverse finishing order. Here discovery starts A, L, B, D, M, P, S, putting A before its prerequisite D. The unreversed finishing list puts L before A. Neither is valid.

A DAG can have many valid orders; this course graph has 34. Different DFS start and neighbor orders may return different valid schedules. A valid topological order is unique exactly when every consecutive pair is joined by a forward edge. If consecutive tasks have no such edge, exchanging them preserves all requirements. A chain through all consecutive pairs instead forces their order.

The same model fits package installation, compilation, and spreadsheet evaluation. Translate the dependency wording first: "v requires u" gives u → v, so the prerequisite appears earlier.

Key Takeaways

  • A topological order places every edge’s source before its target.
  • A full order exists exactly for a DAG.
  • Append vertices when DFS finishes them, then reverse the list.
  • Reject a back edge instead of returning a schedule for a cyclic graph.
  • Validate both vertex membership and every edge’s position inequality.

5.3 Ready tasks and Kahn’s algorithm

Kahn's algorithm builds a topological order from the front. It repeatedly selects a task with no remaining prerequisites. The in-degree counts how many prerequisites still block that task.

Maintain the ready queue
from collections import deque

def topological_kahn(adj):
    indegree = {u: 0 for u in adj}
    for u in adj:
        for v in adj[u]:
            indegree[v] += 1
    ready = deque(u for u in adj if indegree[u] == 0)
    order = []
    while ready:
        u = ready.popleft()
        order.append(u)
        for v in adj[u]:
            indegree[v] -= 1
            if indegree[v] == 0:
                ready.append(v)
    if len(order) != len(adj):
        raise ValueError("Directed cycle")
    return order

Compute in-degrees for every vertex, including isolated ones. Processing u removes its outgoing edges conceptually; subtract from each successor's in-degree, not u's. Each vertex enters the queue once and each edge causes one decrement, for O(V+E) time and O(V) extra space.

Trace a course schedule

For P → D, M → D, D → A, M → A, D → B, A → L, S → L, the initial in-degrees are A 2, B 1, D 2, L 2, M 0, P 0, S 0. Begin with M, P, S in that queue order, and process each successor list alphabetically.

RemovedChanges that matterQueue afterward
MD becomes 1; A becomes 1P, S
PD becomes 0S, D
SL becomes 1D
DA and B become 0A, B
AL becomes 0B, L
BNo outgoing edgeL
LNo outgoing edgeEmpty

The output is M, P, S, D, A, B, L. Both methods may choose among independent tasks, so this need not match the DFS order.

Interpret a stalled queue

If the queue empties before all V vertices are output, the digraph has a cycle. Every remaining vertex has an incoming edge from the remaining subgraph; following those predecessors eventually repeats a vertex. Some blocked vertices can also be downstream of a cycle without lying on it.

Add L → D to the course graph. Kahn's algorithm outputs only M, P, S, then stalls. D → A → L → D is circular. B remains too because it depends on D, although B is not on the cycle. Report that no complete order exists; the short prefix is only the work that can be scheduled before the blockage.

Choose ties and parallel rounds

A FIFO queue gives one valid order. A min-heap, using heapq, always selects the smallest currently available label and gives the alphabetically first order. For the acyclic course graph this is M, P, D, A, B, S, L. The heap adds a logarithmic cost per vertex, giving O(E+Vlog⁡V) time.

For parallel rounds, process all currently ready tasks as one batch, then use newly ready tasks in the next batch. The rounds are {M, P, S}, {D}, {A, B}, {L}. With unit-duration tasks and enough workers, four rounds are necessary: P → D → A → L is a four-task chain. Tasks that become ready during a round do not belong to that same round.

DFS and Kahn both order DAGs in linear time with adjacency lists. Kahn exposes ready tasks directly and avoids recursion; DFS fits a program already collecting finishes and checking active-path edges.

Key Takeaways

  • Initialize the queue with every zero-in-degree vertex.
  • Removing u decrements the in-degrees of its successors.
  • A short output proves a directed cycle, but not every leftover vertex lies on that cycle.
  • A min-heap selects the smallest available task at each step.
  • Batch ready vertices to form parallel rounds for unit-duration tasks.
  • FIFO Kahn and DFS both take O(V+E) time with adjacency lists.

Graph Traversal examples

5 Walkthroughs

1

Build a graph a program can search

12 steps
Choose the meaning of edges, build storage, and generate legal grid moves.
  1. 1
    IntroductionFrom a network to searchable data

    A graph search needs two things: a way to identify vertices and a way to find the next legal moves. We will first decide what links mean, then store them in lists and a matrix. A grid will show how the same information can be generated when needed. Keep direction in view throughout: an arrow supplies one move, while an undirected edge supplies a move each way.

  2. 2
    ExampleCount edges at their endpoints

    Take undirected edges A–B, A–C, B–D, C–D, C–E, D–F, E–F. There are six vertices and seven edges. C touches A, D, and E, so its degree is 3. The degrees 2, 2, 3, 3, 2, 2 sum to 14. Each edge contributes twice to that sum, once at each endpoint; this is the handshake lemma.

  3. 3
    ExplanationCount moves along a route

    The route A–B–D–F lists four vertices but uses three edges, so its length is 3. It is a simple path because no vertex repeats. A–B–D–C–A is a cycle: it returns to A without repeating another vertex or an edge. Traversing A–B and immediately returning on the same undirected edge is not a cycle.

  4. 4
    ChallengeCheck a directed route

    A digraph has only R → S, S → T, and R → T. Can T reach R? Is there a directed cycle?

    ---reveal---

    T cannot reach R because it has no outgoing edge. There is no directed cycle: every route ends at T. Ignoring directions would create a triangle, but that changes the graph and the question being answered.

  5. 5
    ExampleBuild outgoing lists

    For edges 0 → 1, 0 → 2, 1 → 2, 2 → 3, 3 → 1, initialize four empty lists and append each target to its source’s list. The result is [[1, 2], [2], [3], [1]]. For an undirected input, also append each source to its target’s list. Initialize all vertices before adding edges so vertices without links remain represented.

  6. 6
    ExampleRead the matrix by row

    The same directed graph has rows 0 1 1 0, 0 0 1 0, 0 0 0 1, and 0 1 0 0. Row 0 marks outgoing neighbors 1 and 2. Column 1 has two ones because vertices 0 and 3 point to 1. A matrix records every possible pair, so this four-vertex example reserves 16 cells to describe five edges.

  7. 7
    Key InsightMatch the storage to the operation

    A list enumerates only existing neighbors; a matrix must scan a full row. This gives full traversal costs of O(V+E) and O(V2) respectively. A matrix instead tests a particular edge in constant time. On a sparse graph, saving those empty matrix cells usually matters more than making individual edge queries direct.

  8. 8
    ChallengePreserve an isolated vertex

    Vertices are 0, 1, 2, 3, with the single undirected edge 0–2. What adjacency lists preserve the whole graph?

    ---reveal---

    Use [[2], [], [0], []]. Both edge directions must be recorded, and vertices 1 and 3 need empty lists. Building a vertex collection only from the edge endpoints would discard those two vertices and later undercount components.

  9. 9
    ExampleGenerate a legal grid neighbor

    Use a four-way grid with rows ..#, #.., .... From (0, 1), the candidates are (−1, 1), (1, 1), (0, 0), and (0, 2). Reject the first for leaving the grid and the last for entering a wall. The legal neighbors are (1, 1) and (0, 0). Check bounds before indexing: a Python negative index can silently read the last row.

  10. 10
    ExplanationLet states generate their own edges

    An implicit graph calculates neighbors when a search requests them. A four-dial lock state can be the complete digit string. One move turns one digit up or down with wraparound, giving eight neighbors per state. The search stores visited strings and generates the next strings without building all 40,000 undirected edges beforehand.

  11. 11
    ChallengeCombine the model and representation

    A robot can move between open cells up, down, left, and right. You need its fewest moves to a target. What do vertices and edges represent, and must every edge be stored?

    ---reveal---

    Vertices are open cells and edges are legal one-cell moves. The moves are reversible, so the graph is undirected. A neighbor function can generate moves on demand, and BFS can search that implicit graph for the fewest moves.

  12. 12
    RecapA graph model ready for search

    State what one vertex and one edge mean, and preserve direction in every move. Lists store existing neighbors, while matrices reserve every vertex pair. Keep isolated vertices in either representation. For grids and puzzles, generating neighbors can avoid separate edge storage; bounds, obstacles, and complete state information determine whether those generated moves are valid.

2

Trace BFS and recover a shortest route

13 steps
Follow queue changes, record parents, and extend the search to several sources.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionExplore in layers
  2. 2
    ExplanationCreate the first frontier
  3. 3
    ExampleProcess the first layer
  4. 4
    ExampleFinish the outer layers
  5. 5
    ChallengeSpot duplicate pending work
  6. 6
    TipKeep queue operations constant-time
  7. 7
    ExplanationRecord how each layer was reached
  8. 8
    Key InsightWhy a later route cannot be shorter
  9. 9
    ExampleRead parents backward, display forward
  10. 10
    ChallengeApply the distance rule
  11. 11
    ConnectionBegin from several places
  12. 12
    ChallengeChoose direction and meaning of distance
  13. 13
    RecapWhat the BFS result guarantees
3

Follow DFS into and out of branches

15 steps
Trace recursive calls, distinguish stack variants, and use time intervals and edge states.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionFollow a branch, then return
  2. 2
    ExampleEnter the first deep branch
  3. 3
    ExampleFinish calls on the way back
  4. 4
    ExplanationManage pending entries with a stack
  5. 5
    ChallengeWhen does marking change the tree?
  6. 6
    TipSeparate two stack memory bounds
  7. 7
    ExplanationAdd a clock and three states
  8. 8
    ExampleBuild a small time trace
  9. 9
    Key InsightRead ancestry from nested intervals
  10. 10
    ExampleClassify the five directed edges
  11. 11
    ChallengeCheck an interval claim
  12. 12
    ConnectionCompare what the searches return
  13. 13
    ChallengeChoose under a changed graph shape
  14. 14
    ChallengeSelect the result before the implementation
  15. 15
    RecapUse the structure the task needs
4

Separate components and reverse directed routes

11 steps
Label groups once and test whether arrows allow a route in both directions.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionAsk which direction the route must go
  2. 2
    ExampleLabel the first two groups
  3. 3
    ExampleKeep the isolated vertex
  4. 4
    Key InsightCheck components against the edge count
  5. 5
    ChallengeCount regions with a fixed neighbor rule
  6. 6
    ExampleA route out need not return
  7. 7
    ExplanationReverse every arrow
  8. 8
    ChallengeFind a missing return route
  9. 9
    Key InsightWhy one pair of searches is sufficient
  10. 10
    ChallengeUse reversal for dependencies
  11. 11
    RecapSeparate membership from direction
5

Find a cycle or build a valid task order

17 steps
Use the right cycle test, reverse DFS finishes, and remove ready tasks with Kahn’s algorithm.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionTurn traversal into a schedule
  2. 2
    ExampleIgnore the undirected parent entry
  3. 3
    ExplanationUse gray for a directed cycle
  4. 4
    ExampleRecover the circular route
  5. 5
    ChallengeDistinguish two routes from a return
  6. 6
    ExplanationState the order every arrow requires
  7. 7
    ExampleStart the course DFS
  8. 8
    ExampleReverse the completed finish list
  9. 9
    Key InsightWhy the reversal works
  10. 10
    ChallengeCheck a proposed order
  11. 11
    ExplanationCount remaining prerequisites
  12. 12
    ExampleUnlock D after two requirements
  13. 13
    ExampleComplete the queue order
  14. 14
    ChallengeInterpret the blocked remainder
  15. 15
    ConnectionChoose ties or parallel rounds
  16. 16
    ChallengeConnect readiness and order uniqueness
  17. 17
    RecapValidate a schedule or explain the blockage

Graph Traversal practice questions

40 Practice Questions in 4 sets

Set 1: Represent graphs and trace searches10 Practice Questions

Question 1 of 10

An undirected graph has edges J–K, J–L, K–M, L–M. Recursive DFS starts at J and takes neighbors alphabetically. What is its discovery order?
  1. J, K, M, L
  2. J, K, L, M
  3. J, L, K, M
  4. J, M, K, L
Show answerHide answer
Answer: A
DFS enters K from J, then M from K, then L from M before returning to J. The order J, K, L, M would process J’s neighbors as a breadth-first layer. DFS instead completes the active branch before it resumes the earlier vertex’s remaining neighbor loop.

Question 2 of 10

When directed DFS examines u → v, v is gray. What type of edge is it?
  1. Tree edge
  2. Forward edge
  3. Cross edge
  4. Back edge
Show answerHide answer
Answer: D
A gray vertex is discovered but unfinished, so it lies on the current recursive path. The edge returns to that active path and is a back edge. A forward edge instead reaches a descendant that has already finished; being visited alone does not distinguish the two.

Question 3 of 10

A simple undirected graph has degrees 3, 3, 2, 2, 2, 0. How many edges does it have?
  1. 12
  2. 6
  3. 5
  4. 7
Show answerHide answer
Answer: B
The degree sum is 12, and every undirected edge contributes twice, so the graph has 6 edges. Counting 12 edges treats the two endpoints’ contributions as different edges. The isolated vertex contributes zero to the sum but still belongs to the graph.

Question 4 of 10

A digraph has vertices 0, 1, 2 and edges 0 → 2 and 2 → 1. What are its outgoing adjacency lists in vertex order?
  1. [[2], [2], [0, 1]]
  2. [[], [2], [0]]
  3. [[2], [1], []]
  4. [[2], [], [1]]
Show answerHide answer
Answer: D
Vertex 0 points to 2, vertex 1 points nowhere, and vertex 2 points to 1, giving [[2], [], [1]]. Adding return entries would convert the one-way links into undirected edges. The empty list for vertex 1 must remain even though that vertex has no outgoing edge.

Question 5 of 10

An undirected graph has vertices 0–6 and edges 0–1, 1–2, 3–4. How many connected components does it have?
  1. 2
  2. 4
  3. 3
  4. 5
Show answerHide answer
Answer: B
The components are {0, 1, 2}, {3, 4}, {5}, and {6}, giving four. Counting only the groups containing an edge gives two and loses both isolated vertices. A component is a connected piece of vertices, so a single vertex with no edges still counts.

Question 6 of 10

A fully open 3 × 6 grid permits only horizontal and vertical moves. How many undirected edges does its graph have?
  1. 27
  2. 36
  3. 18
  4. 54
Show answerHide answer
Answer: A
Each of the three rows contributes five horizontal edges, and each of the six columns contributes two vertical edges, totaling 27. The 18 cells count vertices, not edges. Counting both travel directions separately would give 54 adjacency entries, twice the undirected edge count.

Question 7 of 10

BFS has queue [L, M]. L has just discovered N and marked it. M also has an edge to N. What should happen when M examines that edge?
  1. Enqueue N again behind its first entry.
  2. Remove N’s first entry and enqueue it again.
  3. Skip N because it is already marked.
  4. Process N before the older queue entries.
Show answerHide answer
Answer: C
N was marked on discovery, so M skips it even though N has not yet been processed. Enqueueing it again would create duplicate pending work. BFS uses discovery to prevent repeated insertions, while the FIFO queue keeps earlier discoveries ahead of later ones.

Question 8 of 10

A digraph has R → S, R → T, S → W, T → U, U → W, W → Z. What is the fewest-edge distance from R to Z?
  1. 2
  2. 4
  3. 3
  4. 5
Show answerHide answer
Answer: C
The route R → S → W → Z has three edges. The route through T and U has four, so it can be a valid DFS route without being shortest. A two-edge route would need a direct edge from S or T to Z, and no such edge is present.

Question 9 of 10

A digraph has H → I, H → J, I → K, J → K. What does a second encounter with K from J establish about cycles?
  1. It establishes no cycle by itself.
  2. It establishes a cycle through H.
  3. It establishes a cycle through J.
  4. It establishes a two-edge cycle at K.
Show answerHide answer
Answer: A
The two routes from H merge at K, but none of the given edges returns from K to an earlier vertex. Encountering a previously finished K therefore does not establish a directed cycle. Directed DFS needs an edge to a gray vertex on its active path, not merely to any visited vertex.

Question 10 of 10

A DAG has vertices A, B, C, D and edges A → C, B → C, C → D. How many complete topological orders does it have?
  1. 1
  2. 3
  3. 4
  4. 2
Show answerHide answer
Answer: D
A and B must both precede C, and C must precede D, so only A, B, C, D and B, A, C, D work. The freedom to choose A or B first prevents uniqueness. C cannot be moved earlier or D inserted before C because those changes violate explicit dependency edges.
Set 2: Apply searches to routes and groups10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

Kahn’s algorithm outputs U, whose outgoing edges are U → V and U → W. Which in-degrees must be decremented?
  1. U’s and V’s
  2. Only U’s
  3. V’s and W’s
  4. Only W’s
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A graph has 200,000 vertices and 500,000 undirected edges. Its main workload is full traversal. What storage and traversal bound fit it best?
  1. Adjacency matrix; O(V+E) time.
  2. Adjacency lists; O(V2) time.
  3. Adjacency lists; O(V+E) time.
  4. Adjacency matrix; O(E) time.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A BFS parent map is {"N": None, "P": "N", "Q": "P", "T": "Q"}. What source-to-T path does it encode?
  1. N → P → Q → T
  2. T → Q → P → N
  3. N → Q → P → T
  4. N → P → T → Q
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A BFS implementation uses a Python list and removes its front item. Starting at the center of an n-vertex star, what worst-case time can the queue removals alone require?
  1. Θ(n)
  2. Θ(n2)
  3. Θ(nlog⁡n)
  4. Θ(1)
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

One-way corridor edges are X → Y, Y → E, Z → Y, E → Z, and W → X. E is the only exit. What are the fewest moves to E from X, Y, Z, and W, in that order?
  1. 2, 1, 1, 3
  2. 1, 2, 1, 2
  3. 2, 1, 2, 2
  4. 2, 1, 2, 3
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A full DFS has finished one search tree. What should its outer loop do when it reaches a vertex already in the shared visited set?
  1. Skip that vertex.
  2. Restart DFS there.
  3. Reset visited set.
  4. Root a new tree.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A puzzle has one legal move per edge and needs a route using the fewest moves. Why does ordinary BFS fit better than stopping at the first DFS solution?
  1. BFS always stores fewer pending states.
  2. DFS cannot reach every reachable state.
  3. BFS reaches states in increasing move count.
  4. DFS examines more edges in every graph.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

An undirected graph has 12 vertices and 4 connected components. It is acyclic. How many edges does it have?
  1. 11
  2. 12
  3. 16
  4. 8
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A digraph has U → V, V → W, W → V, and X → U. What vertices can reach U, including U itself?
  1. U, V, and W
  2. U and X
  3. U, V, W, and X
  4. V and W
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A digraph has R → S, S → T, T → R, T → U, and V → U. DFS starts alphabetically and uses alphabetical neighbors. What cycle is found, and what does T → U show about U?
  1. R → S → T → U → R; U lies on it.
  2. R → S → T → R; U need not lie on it.
  3. S → T → U → S; U lies on it.
  4. R → S → T → R; U must also lie on it.
Show answerHide answer

Save this lesson to see this answer.

Set 3: Reason about paths and dependencies10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A simple digraph on 7 vertices has exactly one arrow for each ordered pair of different vertices. How many edges does it have?
  1. 21
  2. 49
  3. 14
  4. 42
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A lock has three dials showing 0–9. A move turns one dial one step up or down with wraparound. From "000", what is the fewest-move distance to "981"?
  1. 5
  2. 4
  3. 3
  4. 6
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

BFS starts at P in a digraph with P → Q, P → R, Q → S, R → S, R → T. Neighbors are alphabetical. What is the queue immediately after R is processed?
  1. S, S, T
  2. Q, S, T
  3. S, T
  4. T, S
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

An undirected graph has edges J–K, J–L, K–M, L–N, M–P, N–P. BFS starts at J with alphabetical neighbors. What parent does P receive, and would reversing neighbor order change its distance?
  1. Parent N; distance remains 3.
  2. Parent M; distance remains 3.
  3. Parent M; distance becomes 4.
  4. Parent K; distance remains 2.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

DFS gives u discovery/finish times 2/11 and v times 4/7. What ancestry relationship do these intervals establish?
  1. v is a descendant of u.
  2. u is a descendant of v.
  3. They belong to separate trees.
  4. They are necessarily adjacent.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A program only needs to label components of a static undirected graph. What full-traversal time can it obtain with BFS or DFS using adjacency lists?
  1. Only DFS can take O(V+E).
  2. Only BFS can take O(V+E).
  3. Both require O(VE).
  4. Both can take O(V+E).
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

An undirected graph has 10 vertices, 8 edges, and 3 connected components. How many edges must be removed at minimum to leave a forest while preserving those components?
  1. 1
  2. 0
  3. 2
  4. 3
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A digraph has A → B, B → C, C → A, C → D, D → E, E → D. What single added edge would make the whole graph strongly connected?
  1. A → D
  2. B → E
  3. D → A
  4. D → E
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A DAG on R, S, T, U finishes vertices in the order T, S, U, R during a full DFS. What order does DFS topological sorting return?
  1. T, S, U, R
  2. R, S, U, T
  3. U, R, S, T
  4. R, U, S, T
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A dependency graph has vertices J, K, L, M and edges J → L, K → L. Which vertices enter Kahn’s initial ready queue?
  1. J, K, M
  2. J, K
  3. L, M
  4. J, K, L, M
Show answerHide answer

Save this lesson to see this answer.

Set 4: Diagnose traversal and scheduling behavior10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A simple undirected graph has five vertices and every pair is adjacent. What is each vertex’s degree?
  1. 4
  2. 5
  3. 10
  4. 8
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

An implementation stores a V-by-V adjacency matrix but scans only rows belonging to reached vertices. A search reaches r vertices. What row-scanning work and allocated matrix space does it require?
  1. Θ(r+E) work; Θ(V2) space.
  2. Θ(rV) work; Θ(rV) space.
  3. Θ(rV) work; Θ(V2) space.
  4. Θ(r2) work; Θ(V2) space.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A maze state records only the robot’s cell, but opening a door consumes a key that the robot may or may not hold. What information is missing from the state model?
  1. The total number of grid rows.
  2. The order of all previously visited cells.
  3. The full stored matrix of legal moves.
  4. The robot’s current key possession.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

An undirected triangle has alphabetical vertices and neighbors A, B, C. Push-all DFS starts at A, marks on first pop, and pushes neighbors in reverse order. When C is first popped, what parent is recorded for C and what entry remains pending?
  1. Parent A; C from B remains.
  2. Parent B; C from A remains.
  3. Parent B; no entry remains.
  4. Parent A; no entry remains.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A full directed DFS gives R 1/8, S 2/5, T 3/4, U 6/7, V 9/10 as discovery/finish times. The graph contains non-tree edges R → T and V → S. What types are those two edges, respectively?
  1. Back and cross
  2. Forward and back
  3. Tree and forward
  4. Forward and cross
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

Ordinary DFS stops when it first discovers a target after following six edges. What does that result establish about reachability and shortest distance?
  1. The shortest distance is exactly six.
  2. A route exists; shortest distance is unresolved.
  3. No route with fewer than six edges exists.
  4. BFS must also return the same parent chain.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A nonempty digraph has a vertex s that reaches every vertex. In the reverse graph, s also reaches every vertex. Why does this establish a route from an arbitrary u to an arbitrary v in the original?
  1. Combine s → … → u with v → … → s.
  2. Combine u → … → s with v → … → s.
  3. Combine u → … → s with s → … → v.
  4. Combine s → … → u with s → … → v.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A digraph has disconnected parts {A, B} and {X, Y}, with edges A → B, X → Y, Y → X. A cycle test searches only from A. What is required to make its result complete?
  1. Continue from every still-unvisited vertex.
  2. Reverse A → B and repeat from A.
  3. Treat B’s lack of outgoing edges as a cycle.
  4. Check only vertices reached from B.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A DAG has the valid topological order K, L, M, N. It contains edges K → L and M → N but no edge L → M. Is the order unique?
  1. Yes; K → L fixes the entire order.
  2. Yes; every DAG has one fixed order.
  3. No; K, M, L, N is also valid.
  4. No; N, M, L, K is also valid.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

Unit-duration tasks have edges P → R, Q → R, Q → S, R → T, S → U, T → V, U → V. With enough workers, what is the minimum number of parallel rounds?
  1. 3
  2. 4
  3. 5
  4. 6
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

72 Key Terms, each with its definition

A

Active path
The active path is the sequence of entered but unfinished DFS vertices, from the current search root down to the call being explored.
Recursive or iterator-frame DFS stores a long active path on a chain and a short one in a shallow tree.
Adjacency list
An adjacency list stores a neighbor collection for each vertex, recording outgoing neighbors when the graph is directed.
A directed vertex with no outgoing edges still receives an empty list in the representation.
Adjacency matrix
An adjacency matrix is a square table whose row-u, column-v entry records whether an edge goes from vertex u to vertex v.
In a zero-one matrix, summing row u counts outgoing edges and summing column u counts incoming edges.
Auxiliary space
Auxiliary space is the extra memory an algorithm uses beyond its input representation, including visited data and pending work.
A push-all DFS stack can contain duplicate pending entries, increasing its worst-case auxiliary space.

B

Back edge
A back edge in directed DFS points to a gray vertex on the active path, completing a directed cycle through that path.
The arrow from a deep call to its still-active ancestor is a back edge even when other branches exist.
Backtracking
Backtracking returns from a completed branch to an earlier choice point so a depth-first process can explore an untried alternative.
After a vertex has no new neighbor, DFS resumes the paused neighbor loop in its parent.
BFS tree
A BFS tree consists of the source and its discovery-parent edges, giving one shortest unweighted path to every vertex reached from that source.
Changing neighbor order can change the BFS tree while leaving every recorded distance unchanged.
Breadth-first search
Breadth-first search (BFS) explores reachable vertices in increasing unweighted distance layers by processing a first-in, first-out queue.
A search for everyone within two social links stops expanding after the second distance layer.

C

Component label
A component label assigns the same identifier to all vertices in one undirected component, allowing constant-time connection queries afterward.
Two devices with different component labels cannot communicate through any route in that network.
Connected component
A connected component is a largest group of undirected vertices in which every pair is joined by a path, including a lone isolated vertex.
Scanning all vertices and searching from each unlabeled start gives one search per connected component.
Cross edge
A cross edge is a directed DFS edge to an earlier finished vertex that is neither an ancestor nor a descendant of the source.
A later DFS tree may point into an earlier finished tree without creating a directed cycle.
Cycle
A cycle is a closed route that repeats no vertex except its start and end and uses no edge twice; directed cycles follow arrows.
The arrows "X → Y → Z → X" give a circular dependency that prevents a complete task order.
Cycle reconstruction
Cycle reconstruction recovers a cycle’s vertices from a detected back edge and the parent chain leading to its active ancestor.
For a back edge from W to R, reverse the parents from W to R and append R to close the route.

D

Degree
The degree of an undirected vertex is the number of incident edges; directed vertices have separate incoming and outgoing counts.
A device linked directly to three other devices has degree 3, even if many more devices are reachable.
Dense graph
A dense graph has an edge count close to the maximum possible for its vertex count, so many vertex pairs are directly joined.
When nearly every device links directly to every other device, a matrix can be a practical choice.
Depth-first search
Depth-first search (DFS) follows an unvisited branch as far as possible, then backtracks to explore the remaining neighbors of earlier vertices.
A recursive DFS returns from a leaf before continuing the neighbor loop in the leaf’s parent call.
DFS forest
A DFS forest is the collection of search trees produced by a full DFS that starts a new tree at each still-unvisited vertex.
In an undirected graph each tree spans one component; directed search trees need not be strongly connected.
Directed acyclic graph
A directed acyclic graph (DAG) is a digraph with no directed cycle, exactly the kind of graph that admits a complete topological order.
A dependency diamond is a DAG even though two different routes can lead to the same final task.
Directed cycle
A directed cycle is a closed route following arrows without repeating another vertex, including a self-loop or two opposite directed edges.
A dependency chain returning to its first task prevents those tasks from receiving a valid topological order.
Directed graph
A directed graph, or digraph, has edges with a source and target, so allowed routes must follow each edge’s arrow direction.
A route from a page to a linked page does not establish that the linked page can reach back.
Discovery
Discovery is the first time a search reaches a vertex; ordinary BFS marks the vertex then, immediately before enqueueing it.
Two processed vertices can share a neighbor, but only the first discovery adds it to the BFS queue.
Discovery time
A discovery time is the clock value assigned when DFS first enters a vertex, before examining that vertex’s outgoing neighbors.
If a descendant enters after its ancestor, its discovery time is larger and its finishing time is smaller.

E

Edge
An edge is a direct link between vertices; it can be undirected for a two-way relation or directed for a one-way relation.
The arrow "Load → Parse" records that loading must happen before parsing can begin.
Eight-neighborhood
The eight-neighborhood adds the four diagonal neighbors to a grid cell’s orthogonal neighbors, subject to bounds and obstacles.
Diagonal land contacts can merge islands when a map changes from four-way to eight-way movement.

F

Finishing time
A finishing time is the clock value assigned when DFS completes a vertex after every recursive neighbor exploration has returned.
Reversing the finishing sequence gives a topological order when the directed graph has no cycle.
Flood fill
Flood fill searches the connected grid region containing a starting cell, following a fixed rule for which neighboring cells belong together.
A paint-bucket operation recolors the cells connected to the clicked cell under its chosen neighbor rule.
Forest
A forest is an acyclic undirected graph whose connected components are trees; with V vertices and c components it has V − c edges.
Three separate trees form a forest even though the full collection is not a connected graph.
Forward edge
A forward edge is a non-tree directed edge from a vertex to one of its DFS descendants, examined after that descendant has finished.
A direct shortcut to a descendant reached through another branch can be classified as a forward edge.
Four-neighborhood
The four-neighborhood of a grid cell consists of its orthogonal neighbors above, below, left, and right, subject to bounds and obstacles.
Two land cells touching only at a corner remain in separate regions under four-way flood fill.
Frontier
The frontier is the discovered work waiting to be processed; in BFS it is stored in a queue and may span two consecutive distance layers.
Searching from the center of a large star places all its leaves in the frontier at once.

G

Graph
A graph is a collection of vertices and edges that models objects and the direct relationships or permitted moves between them.
A network model uses devices as vertices and direct cable links as edges between those devices.
Gray vertex
A gray vertex has been discovered by DFS but has not finished, so it belongs to the active chain of recursive calls or iterator frames.
A directed edge to a gray vertex returns to the current path and reveals a directed cycle.

I

Implicit graph
An implicit graph generates a vertex’s neighbors when needed, allowing a search to follow edges without storing all of them beforehand.
A maze search computes legal moves from the current cell instead of building an adjacency table.
In-degree
The in-degree of a directed vertex is the number of edges entering it, such as the number of direct prerequisites for a task.
A task required by nobody may still have in-degree 2 because it depends on two earlier tasks.
Isolated vertex
An isolated vertex has no incident edges and forms a connected component by itself in an undirected graph.
Creating the vertex collection only from edge endpoints would omit a device with no links.
Iterator frame
An iterator frame stores an active vertex and its next neighbor position, allowing iterative DFS to pause and resume like recursion.
When a frame has no neighbor left, the vertex finishes and the frame is removed from the stack.

K

Kahn’s algorithm
Kahn’s algorithm builds a topological order by repeatedly outputting a vertex with zero remaining in-degree and removing its outgoing edges.
A successor enters the ready collection only after the last of its unscheduled prerequisites is removed.

M

Min-heap
A min-heap keeps its smallest element available for removal, allowing Kahn’s algorithm to choose the smallest currently ready label.
A newly ready task can precede an older waiting task when its label is smaller in the min-heap.
Multi-source BFS
Multi-source BFS initializes several sources at distance zero and searches once to find each reached vertex’s distance from its nearest source.
Starting from several exits in a reversed corridor graph gives fewest-move routes toward an exit.

O

Order validation
Order validation checks that every vertex appears once and that every dependency arrow points from an earlier to a later position.
A schedule that omits an isolated task can pass edge checks but still fail complete-order validation.
Out-degree
The out-degree of a directed vertex is the number of edges leaving it, equal to the length of its outgoing neighbor list.
If a page links to four different pages, its out-degree is 4 even when no page links back.

P

Parallel edges
Parallel edges are distinct edges joining the same vertex pair in the same direction, allowing multiple links where a simple graph allows one.
An undirected cycle test may need edge identities when two separate cables join the same devices.
Parallel round
A parallel round groups tasks ready at the same stage, with successors unlocked by that group deferred until the following round.
With unit-duration tasks and enough workers, a chain of five tasks requires at least five rounds.
Parent edge
A parent edge is the DFS tree edge used to enter a vertex; its reverse adjacency entry must be excluded in a simple undirected cycle test.
An undirected child sees its parent as visited, but that alone does not establish a cycle.
Parent pointer
A parent pointer records the vertex from which another vertex was first discovered, letting a search reconstruct a route back to its start.
Following parents from a BFS target returns the shortest route in reverse, ready to be reversed for display.
Path
A path is a vertex sequence linked by consecutive edges, following arrow directions in a digraph; its length counts the edges.
The route "R–S–T–U" lists four vertices and has length 3 because it makes three moves.
Postorder
Postorder lists vertices in increasing DFS finishing time, recording each vertex after the neighbor explorations it starts have completed.
On a DAG, reversing the postorder gives a topological order; leaving it unchanged reverses dependencies.
Preorder
Preorder lists vertices in their DFS discovery order, recording each vertex before the search recursively explores its unvisited neighbors.
A preorder can begin with a task that has incoming prerequisite edges, so it need not be topological.
Prerequisite
A prerequisite is a task that must finish before another task starts, represented by an arrow from the earlier required task to its successor.
The statement "Test requires Build" becomes the edge "Build → Test" before a topological sort.

Q

Queue
A queue processes the earliest added waiting item first; BFS uses this order to process shorter-distance discoveries before longer ones.
After the source adds its neighbors, those neighbors wait ahead of any newly discovered distance-2 vertices.

R

Reachability
Reachability means that a route exists from one vertex to another, following edge directions whenever the graph is directed.
BFS and DFS can both decide whether a target is reachable without requiring the same discovery order.
Ready vertex
A ready vertex has zero in-degree in the remaining dependency graph, so all its prerequisites have already been scheduled or none existed.
A task can become ready midway through Kahn’s algorithm even when it was initially blocked.
Residual graph
The residual graph in Kahn’s algorithm consists of the unscheduled vertices and their remaining edges after some ready vertices are removed.
If the ready queue is empty but the residual graph is nonempty, a directed cycle remains.
Reverse graph
The reverse graph preserves every vertex and flips every directed edge, turning original routes into routes in the opposite direction.
Searching outward from a target in the reverse graph finds all original vertices that can reach it.
Reverse postorder
Reverse postorder lists DFS vertices from latest finish to earliest finish and gives a topological order when applied to a DAG.
Appending vertices on return and reversing the list places a course before all courses that depend on it.

S

Self-loop
A self-loop is an edge from a vertex to itself; in a digraph it forms a cycle of length 1 and points to gray during DFS.
A task requiring itself creates a self-loop even when every other dependency is acyclic.
Shortest-path tree
A shortest-path tree gives a shortest route from its root to each reached vertex; BFS constructs one when distance means number of edges.
Two equal-length routes to a target allow different valid parents in a shortest-path tree.
Simple graph
A simple graph has no self-loops and no parallel edges, so a permitted vertex pair has at most one edge of a given direction.
A simple undirected graph on five vertices can contain at most ten distinct edges.
Simple path
A simple path is a path that repeats no vertex, so a sequence of k listed vertices along it contains exactly k − 1 edges.
The route "A–D–B" is simple, while "A–D–B–D" revisits D and is not a simple path.
Sparse graph
A sparse graph has far fewer edges than the maximum possible for its number of vertices, making neighbor lists useful for storage.
A large road network can be sparse because most intersections meet only a few road segments.
Stack
A stack removes the most recently added item first; DFS can use it to store active frames or pending vertices instead of recursive calls.
Pushing a neighbor list in reverse makes its first listed neighbor pop before the later ones.
State-space graph
A state-space graph represents complete system states as vertices and individual legal moves as edges between those states.
A lock position records all four dial digits so the next legal turns can be generated.
Strong connectivity
Strong connectivity means every vertex in a digraph can reach every other vertex along directed paths, providing routes in both directions.
One start reaching all vertices is insufficient if a reached dead end cannot return to that start.
Symmetric matrix
A symmetric matrix has matching entries across its main diagonal; an undirected adjacency matrix has this property for every vertex pair.
Recording an undirected edge requires setting both the u-v cell and the v-u cell.

T

Topological order
A topological order lists every vertex of a digraph once so that each directed edge goes from an earlier vertex to a later vertex.
Independent tasks can exchange positions while every prerequisite still appears before its successor.
Tree
A tree is a connected, acyclic undirected graph; with n vertices it has n − 1 edges and a unique simple path between each pair.
Removing one edge from a tree separates it into two pieces because no alternate route crosses that edge.
Tree edge
A tree edge is an edge through which DFS first discovers its target, making the source the target’s parent in the search forest.
If DFS sees an edge into a white vertex, entering that vertex makes the edge a tree edge.

U

Unweighted distance
The unweighted distance from one vertex to another is the fewest edges on any directed or undirected route allowed by the graph.
A route visiting six cells uses five moves, so its distance is 5 if no shorter route exists.

V

Vertex
A vertex, also called a node, is one object or complete state in a graph, identified separately from the edges that join it to others.
An isolated server remains a vertex even when no communication link connects it to another server.
Vertex indexing
Vertex indexing assigns each vertex a numeric position so arrays or matrix rows and columns can represent named or numbered vertices.
A fixed mapping from task names to integers keeps the matrix aligned with the original dependency data.

W

Weak connectivity
Weak connectivity means that a digraph becomes connected after its arrows are ignored and each edge is treated as undirected.
A one-way chain is weakly connected even though its last vertex cannot reach its first.
Weighted graph
A weighted graph assigns a numeric cost or distance to each edge; ordinary BFS minimizes edge count without comparing these weights.
A direct expensive link can have fewer edges than a cheaper route through an intermediate vertex.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started