Graphs and Graph Traversal
IntermediateLesson 8 of 10 in Data Structures and Algorithms Course
What you will learn
- 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 graphsName 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 matrixBuild 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 graphsDecide 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.
- Use the vocabulary of graphs
- 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 queueCarry 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 BFSRecord 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.
- Run breadth-first search with a queue
- 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 stackTrace 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 timesRecord 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 DFSCompare the two searches on visit order, paths, memory and typical uses, and pick the one that answers a given question.
- Run depth-first search recursively and with a stack
- 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 graphLabel 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 graphsFind 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.
- Find the connected components of an undirected graph
- 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 graphsUse 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 sortExplain when a topological order exists, find one from DFS finishing times, and check any proposed order against the edges.
- Order tasks with Kahn's algorithmRepeatedly remove tasks with no remaining prerequisites, use the result to detect a cycle, and compare this queue-based method with the DFS method.
- Detect cycles in undirected and directed graphs
Graph Traversal study guide
1Describe 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 names the vertex set and edge set. In a cost such as , 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 . Each directed edge contributes once to the total in-degree and once to the total out-degree; each total equals .
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 vertices, a simple undirected graph has at most edges, and a simple directed graph at most . For 10 vertices those bounds are 45 and 90. Thus a simple graph has 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 edges for 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 ; in-degrees and out-degrees each total .
- 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
| Operation | List of neighbors | Matrix |
|---|---|---|
| Storage | ||
| Test u → v | ||
| Enumerate u's neighbors | ||
| Add an edge | Amortized | |
| Remove u → v | ||
| Full BFS or DFS |
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 cells: even one bit per cell totals 125 GB. In 64-bit CPython, a list-of-lists matrix for 10,000 vertices has 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 space and offers average 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 space; matrices use .
- 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 vertices. Horizontal edges number and vertical edges number . 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.
2Search 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.
| Removed | Newly discovered | Queue afterward |
|---|---|---|
| A | B, C | B, C |
| B | D | C, D |
| C | E | D, E |
| D | F | E, F |
| E | None | F |
| F | None | Empty |
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 time for a full traversal. A matrix instead scans V cells per processed vertex and gives worst-case time.
The queue and visited set need 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 time and 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 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.
3Explore 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 time; full matrix traversal takes . Recursive DFS uses 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 pending entries, including duplicates, so its extra space is . To retain the recursive 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 extra space; the push-all stack can need .
- 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.
| Vertex | Discovery | Finish |
|---|---|---|
| A | 1 | 6 |
| B | 2 | 5 |
| C | 3 | 4 |
| D | 7 | 8 |
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 → v | Edge type | Meaning |
|---|---|---|
| White | Tree | Discovers v |
| Gray | Back | Returns to the active path |
Black, d[u] < d[v] | Forward | Reaches a finished descendant |
Black, d[u] > d[v] | Cross | Reaches 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
| Need | Suitable search | Reason |
|---|---|---|
| Decide whether a route exists | BFS or DFS | Both explore the reachable set |
| Fewest edges or equal-cost moves | BFS | Layers increase by one edge |
| Undirected connected components | BFS or DFS | Each start reaches one whole component |
| Discovery and finishing structure | DFS | Calls have nested lifetimes |
| Directed cycle detection | DFS with active states | An edge to gray closes an active path |
| Dependency order | DFS on a DAG, or Kahn's algorithm | Both 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 time. Each visits vertices once and examines each adjacency list once. With a matrix, full traversal takes . 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.
4Solve 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 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 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 time.
- A forest has exactly 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
| Question | Meaning |
|---|---|
| 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 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 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.
5Detect 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 . If connected, this becomes . 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 .
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 time and 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 time and 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.
| Removed | Changes that matter | Queue afterward |
|---|---|---|
| M | D becomes 1; A becomes 1 | P, S |
| P | D becomes 0 | S, D |
| S | L becomes 1 | D |
| D | A and B become 0 | A, B |
| A | L becomes 0 | B, L |
| B | No outgoing edge | L |
| L | No outgoing edge | Empty |
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 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 time with adjacency lists.
Graph Traversal examples
1Build a graph a program can search
12 steps
- 1IntroductionFrom 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.
- 2ExampleCount 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.
- 3ExplanationCount 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.
- 4ChallengeCheck 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.
- 5ExampleBuild 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. - 6ExampleRead the matrix by row
The same directed graph has rows
0 1 1 0,0 0 1 0,0 0 0 1, and0 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. - 7Key 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 and 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.
- 8ChallengePreserve 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. - 9ExampleGenerate 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. - 10ExplanationLet 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.
- 11ChallengeCombine 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.
- 12RecapA 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.
2Trace BFS and recover a shortest route
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionExplore in layers
- 2ExplanationCreate the first frontier
- 3ExampleProcess the first layer
- 4ExampleFinish the outer layers
- 5ChallengeSpot duplicate pending work
- 6TipKeep queue operations constant-time
- 7ExplanationRecord how each layer was reached
- 8Key InsightWhy a later route cannot be shorter
- 9ExampleRead parents backward, display forward
- 10ChallengeApply the distance rule
- 11ConnectionBegin from several places
- 12ChallengeChoose direction and meaning of distance
- 13RecapWhat the BFS result guarantees
3Follow DFS into and out of branches
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionFollow a branch, then return
- 2ExampleEnter the first deep branch
- 3ExampleFinish calls on the way back
- 4ExplanationManage pending entries with a stack
- 5ChallengeWhen does marking change the tree?
- 6TipSeparate two stack memory bounds
- 7ExplanationAdd a clock and three states
- 8ExampleBuild a small time trace
- 9Key InsightRead ancestry from nested intervals
- 10ExampleClassify the five directed edges
- 11ChallengeCheck an interval claim
- 12ConnectionCompare what the searches return
- 13ChallengeChoose under a changed graph shape
- 14ChallengeSelect the result before the implementation
- 15RecapUse the structure the task needs
4Separate components and reverse directed routes
11 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionAsk which direction the route must go
- 2ExampleLabel the first two groups
- 3ExampleKeep the isolated vertex
- 4Key InsightCheck components against the edge count
- 5ChallengeCount regions with a fixed neighbor rule
- 6ExampleA route out need not return
- 7ExplanationReverse every arrow
- 8ChallengeFind a missing return route
- 9Key InsightWhy one pair of searches is sufficient
- 10ChallengeUse reversal for dependencies
- 11RecapSeparate membership from direction
5Find a cycle or build a valid task order
17 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionTurn traversal into a schedule
- 2ExampleIgnore the undirected parent entry
- 3ExplanationUse gray for a directed cycle
- 4ExampleRecover the circular route
- 5ChallengeDistinguish two routes from a return
- 6ExplanationState the order every arrow requires
- 7ExampleStart the course DFS
- 8ExampleReverse the completed finish list
- 9Key InsightWhy the reversal works
- 10ChallengeCheck a proposed order
- 11ExplanationCount remaining prerequisites
- 12ExampleUnlock D after two requirements
- 13ExampleComplete the queue order
- 14ChallengeInterpret the blocked remainder
- 15ConnectionChoose ties or parallel rounds
- 16ChallengeConnect readiness and order uniqueness
- 17RecapValidate a schedule or explain the blockage
Graph Traversal practice questions
Set 1: Represent graphs and trace searches10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
Show answerHide answer
Question 3 of 10
Show answerHide answer
Question 4 of 10
Show answerHide answer
[[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
Show answerHide answer
Question 6 of 10
Show answerHide answer
Question 7 of 10
[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?Show answerHide answer
Question 8 of 10
Show answerHide answer
Question 9 of 10
Show answerHide answer
Question 10 of 10
Show answerHide answer
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
{"N": None, "P": "N", "Q": "P", "T": "Q"}. What source-to-T path does it encode?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Active path
Adjacency list
Adjacency matrix
Auxiliary space
B
Back edge
Backtracking
BFS tree
Breadth-first search
C
Component label
Connected component
Cross edge
Cycle
Cycle reconstruction
D
Degree
Dense graph
Depth-first search
DFS forest
Directed acyclic graph
Directed cycle
Directed graph
Discovery
Discovery time
E
Edge
Eight-neighborhood
F
Finishing time
Flood fill
Forest
Forward edge
Four-neighborhood
Frontier
G
Graph
Gray vertex
I
Implicit graph
In-degree
Isolated vertex
Iterator frame
K
Kahn’s algorithm
M
Min-heap
Multi-source BFS
O
Order validation
Out-degree
P
Parallel edges
Parallel round
Parent edge
Parent pointer
Path
Postorder
Preorder
Prerequisite
Q
Queue
R
Reachability
Ready vertex
Residual graph
Reverse graph
Reverse postorder
S
Self-loop
Shortest-path tree
Simple graph
Simple path
Sparse graph
Stack
State-space graph
Strong connectivity
Symmetric matrix
T
Topological order
Tree
Tree edge
U
Unweighted distance
V
Vertex
Vertex indexing
W
Weak connectivity
Weighted graph
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.