Week 10: Graph Theory, Representations, BFS & DFS
4108 words
21 min read
2026-09-12T00:00:00.000Z
Visual companion
View
Revision summary
What this note is really saying
Short form
Vertices, edges, degrees, handshaking lemma, adjacency matrices/lists, BFS, DFS, trees, DAGs, and topological sorting. # Mathematics I — Week 10: Graph Theory, Representations, BFS & DFS IITM’s Week 10 moves into **graph theory: representation of graphs, breadth-first search, depth-first search, applications of BFS/...

Visual strip
Relevant recall pieces for this note
Mathematics I — Week 10: Graph Theory, Representations, BFS & DFS
IITM’s Week 10 moves into graph theory: representation of graphs, breadth-first search, depth-first search, applications of BFS/DFS, and directed acyclic graphs.
TL;DR
A graph models objects and relationships:
where:
- V = vertices/nodes
- E = edges/connections
The highest-value Week 10 ideas are:
- graph vocabulary
- undirected vs directed graphs
- adjacency representations
- degree / in-degree / out-degree
- paths and connectivity
- BFS
- DFS
- connected components
- cycles
- DAGs
- why BFS and DFS have different behavior
1. What is a graph?
A graph is usually written:
where:
- V is a set of vertices
- E is a set of edges
Example:
and:
This describes:
textA — B — C — D
2. Why graphs matter
Graphs can model:
- social networks
- roads
- airline routes
- web pages and hyperlinks
- computer networks
- dependencies
- family trees
- recommendation systems
- state transitions
- knowledge graphs
The abstraction is:
entities + relationships
3. Undirected graph
In an undirected graph, an edge has no direction.
If:
then A is connected to B and B is connected to A.
Graphically:
textA — B
4. Directed graph
A directed graph or digraph uses directed edges:
meaning:
This does not automatically imply:
Example:
textA → B → C
Directed graphs are useful for:
- follower relationships
- prerequisites
- hyperlinks
- workflows
- dependency graphs
5. Vertex / node
A vertex is one object in the graph.
Plural:
- vertices
- nodes
These terms are often used interchangeably.
6. Edge
An edge represents a relationship between vertices.
Undirected:
Directed:
or:
7. Adjacent vertices
Two vertices are adjacent if an edge connects them.
If:
then:
and:
are adjacent.
8. Neighbors
The neighbors of a vertex are all vertices directly connected to it.
For:
textA — B — C | D
neighbors of B are:
9. Degree of a vertex
In an undirected graph, the degree of vertex v is the number of incident edges.
Notation:
Example:
textA — B — C | D
Then:
And:
10. Handshaking lemma
For an undirected graph:
Why?
Every edge contributes:
to the degree of each of its two endpoints.
So each edge gets counted twice.
11. Consequence: odd-degree vertices
The number of vertices with odd degree is always even.
This follows from the handshaking lemma.
A surprisingly useful graph-theory fact.
12. In-degree and out-degree
For directed graphs:
In-degree
Number of edges entering a vertex.
Out-degree
Number of edges leaving a vertex.
Example:
textA → B ← C ↓ D
For B:
and:
13. Directed degree identity
For a directed graph:
and:
Each directed edge contributes once to total in-degree and once to total out-degree.
14. Walk
A walk is a sequence of vertices where consecutive vertices are connected.
Vertices and edges may repeat.
Example:
This can be a valid walk even though B repeats.
15. Path
A path typically means a walk without repeated vertices.
Example:
Path length is usually the number of edges.
So:
has length:
16. Cycle
A cycle starts and ends at the same vertex, without unnecessary repetition of internal vertices.
Example:
textA — B | | D — C
One cycle:
17. Connected graph
An undirected graph is connected if every pair of vertices has a path between them.
Example:
textA — B — C | D
Everything is reachable from everything else.
So the graph is connected.
18. Disconnected graph
Example:
textA — B C — D
There is no path from A to C.
So the graph is disconnected.
19. Connected components
A connected component is a maximal connected part of a graph.
For:
textA — B C — D — E F
there are:
connected components:
20. Complete graph
A complete graph has an edge between every pair of distinct vertices.
Notation:
For n vertices, the number of edges is:
21. Why?
Each edge corresponds to choosing:
vertices from n.
So:
Example:
has:
edges.
22. Graph representation problem
A graph is an abstract object.
A computer needs a concrete representation.
Two major representations:
- adjacency matrix
- adjacency list
23. Adjacency matrix
For n vertices, create an:
matrix.
Let:
For undirected graphs, the matrix is symmetric.
24. Example
Graph:
textA — B | C
Ordering:
Adjacency matrix:
25. Why diagonal entries are often zero
In a simple graph, there are no self-loops.
So:
If self-loops are allowed, diagonal entries may be nonzero.
26. Symmetry in undirected graphs
If:
then:
and:
Therefore:
for simple undirected graphs.
27. Adjacency list
Instead of storing an entire matrix, store each vertex's neighbors.
Example:
textA — B | C
Adjacency list:
textA: B, C B: A C: A
28. Matrix vs list
Adjacency matrix
Space:
Good for:
- dense graphs
- fast edge existence lookup
Adjacency list
Space:
Good for:
- sparse graphs
- traversal algorithms
Most real-world sparse graphs favor adjacency lists.
29. Edge lookup complexity
With adjacency matrix:
Is there edge (u,v)?
Usually:
With adjacency list:
depends on how neighbors are stored.
Potentially:
30. Graph traversal
Graph traversal means:
systematically visit vertices of a graph.
Two fundamental algorithms:
and:
31. Breadth-First Search
BFS = Breadth-First Search.
Core idea:
Explore the graph layer by layer.
Starting from a source:
- visit source
- visit all neighbors
- visit neighbors of those neighbors
- continue outward
32. BFS mental picture
Suppose:
textA / \ B C / \ \ D E F
Starting BFS at:
a typical traversal:
It visits by distance layers:
33. BFS uses a queue
BFS is naturally implemented using a queue.
Queue behavior:
First In, First Out.
Conceptually:
textenqueue(start) while queue not empty: v = dequeue() for each unvisited neighbor u: mark u visited enqueue(u)
34. Why marking visited matters
Graphs can contain cycles.
Without a visited set:
textA — B | | D — C
the algorithm could keep looping:
So each vertex should generally be marked visited.
35. BFS and shortest paths
One of BFS's most important properties:
In an unweighted graph, BFS finds shortest paths measured by number of edges.
Why?
Because it explores vertices in increasing distance from the source.
First:
edges away.
Then:
edge away.
Then:
edges away.
And so on.
36. Example
Graph:
textA — B — D | | C — E
Start:
Distances:
BFS naturally discovers these layers.
37. BFS applications
Common applications:
- shortest path in unweighted graph
- finding connected components
- network broadcasting
- degree-of-separation problems
- web crawling
- bipartite testing
- level-order exploration
38. Depth-First Search
DFS = Depth-First Search.
Core idea:
Go as deep as possible before backtracking.
From a vertex:
- choose an unvisited neighbor
- explore it
- continue deeper
- when stuck, backtrack
39. DFS mental picture
Using:
textA / \ B C / \ \ D E F
Possible DFS:
Exact order depends on neighbor ordering.
The defining feature is depth-first behavior, not one fixed output sequence.
40. DFS uses a stack
DFS can be implemented using:
- recursion
- explicit stack
Stack behavior:
Last In, First Out.
Recursive pseudocode:
textDFS(v): mark v visited for each neighbor u of v: if u not visited: DFS(u)
41. Backtracking intuition
DFS explores:
textA ↓ B ↓ D
If D has nowhere new to go, it returns:
textD ↑ B
Then explores another branch.
That returning behavior is backtracking.
42. DFS applications
DFS is useful for:
- connected components
- detecting cycles
- topological sorting
- maze exploration
- dependency analysis
- path existence
- structural graph analysis
- strongly connected components in more advanced settings
43. BFS vs DFS
| BFS | DFS |
|---|---|
| breadth first | depth first |
| queue | stack/recursion |
| explores levels | explores branches |
| shortest unweighted path | not generally shortest |
| useful for distance | useful for structure/backtracking |
Neither is universally "better."
They solve different kinds of problems naturally.
44. BFS complexity
Using adjacency lists:
Why?
Each vertex is processed at most once.
Each edge is examined a constant number of times.
45. DFS complexity
Also:
with adjacency-list representation.
So asymptotically BFS and DFS often have the same traversal complexity.
Their behavior and applications differ.
46. Traversal on disconnected graphs
Starting BFS/DFS from one vertex only explores its connected component.
To visit the entire graph:
textfor each vertex v: if v unvisited: BFS(v)
or DFS.
Each new traversal discovers another component.
47. Counting connected components
Initialize:
For every unvisited vertex:
- increment
count - run BFS/DFS from it
At the end:
equals number of connected components.
48. Cycle detection intuition
In an undirected graph during DFS:
If you encounter a visited neighbor that is not the current vertex's parent, you have found a cycle.
In directed graphs, cycle detection requires tracking traversal state more carefully.
49. Trees
A tree is an undirected graph that is:
- connected
- acyclic
A tree with:
vertices always has:
edges.
50. Equivalent tree characterizations
For a finite undirected graph, several statements are equivalent:
- connected and acyclic
- exactly one simple path between every pair of vertices
- connected with ∣V∣−1 edges
- acyclic with ∣V∣−1 edges
These relationships are highly useful.
51. Why trees matter here
BFS and DFS naturally generate search trees.
As you discover new vertices, you can remember which vertex discovered each one.
Those parent relationships form a tree.
52. BFS tree
A BFS tree rooted at source s organizes vertices by distance:
textdistance 0: s distance 1: neighbors distance 2: neighbors of neighbors ...
So it captures shortest unweighted distances.
53. DFS tree
A DFS tree captures the recursive exploration structure.
It is especially useful for reasoning about:
- ancestry
- backtracking
- cycles
- ordering
54. Directed Acyclic Graph
A DAG is a:
So it is:
- directed
- contains no directed cycle
Example:
textA → B → D \ ↑ → C ──
provided there is no route that returns to the starting node following arrow directions.
55. Why DAGs are important
DAGs model dependencies.
Examples:
Courses
textCalculus I → Calculus II
Build systems
textsource → compile → package → deploy
Tasks
textdesign → implement → test → release
Data pipelines
textraw data → clean → transform → train
56. Directed cycle problem
Suppose:
textA → B ↑ ↓ D ← C
Then:
This is a directed cycle.
So the graph is not a DAG.
In a dependency system, this could mean:
A depends on B, B depends on C, ..., and something eventually depends back on A.
That is impossible to resolve sequentially.
57. Topological ordering intuition
A DAG can be arranged so that every directed edge points forward.
Example:
textA → B A → C B → D C → D
One topological ordering:
Another:
Topological order is generally not unique.
58. What topological order means
For every edge:
vertex u must appear before v.
This makes topological ordering ideal for dependency scheduling.
59. A directed graph has a topological ordering iff
For a finite directed graph:
This is a fundamental relationship.
60. BFS-style topological sorting intuition
One approach repeatedly chooses vertices with:
Why?
Such a vertex has no unresolved prerequisites.
Process it, remove its outgoing edges, and repeat.
This is commonly known as Kahn's algorithm.
Even if not required by name, understand the mechanism.
61. DFS-style topological sorting intuition
DFS can also construct a topological order.
Rough idea:
place a vertex after all vertices reachable from it have been processed.
Then reverse finishing order.
This is another example of DFS being useful for structural ordering.
62. Graph traversal ordering is not unique
Suppose A has neighbors:
If the representation lists:
one BFS/DFS order results.
If it lists:
another may result.
Therefore, unless neighbor ordering is specified:
multiple traversal sequences may be valid.
This is a common MCQ trap.
63. Path existence
To determine whether there is a path from:
to:
run BFS or DFS from s.
If:
is visited, a path exists.
If traversal completes without visiting t, no path exists in that reachable component.
64. Recovering a path
During BFS/DFS, store:
When v is first discovered from u:
Then to recover path from source to target:
until source.
Reverse that sequence.
65. BFS shortest-path example
Suppose:
textA — B — D | | C — E — F
From A, BFS might assign:
Then shortest path to F:
Length:
66. Graph as relation — Week 1 connection
Recall Week 1:
A relation:
A directed graph on vertex set V can be viewed as a relation:
So relation theory and graph theory are closely connected.
An edge:
simply means:
67. Adjacency matrix as relation matrix
For a relation:
the adjacency matrix records:
exactly when:
So Week 10 is partly a computational representation of Week 1 relations.
68. Symmetric relation ↔ undirected-style adjacency
If a directed relation is symmetric:
then its adjacency matrix is symmetric.
This mirrors an undirected graph.
Nice connection:
69. Reflexivity ↔ self-loops
Recall:
for every v means reflexive.
Graphically, every vertex would have a self-loop:
text↺ A
So relation properties have natural graph interpretations.
70. Transitivity ↔ shortcut edges
If:
and:
transitivity requires:
So the Week 1 mental model:
every two-step relation requires a shortcut
is literally graph language.
71. Complexity intuition
For graph algorithms, input size is not just:
There may also be many edges:
So traversal complexity:
means work grows roughly with the amount of graph data that actually exists.
This is more informative than saying simply:
for sparse graphs.
72. Sparse vs dense graphs
A sparse graph has relatively few edges.
Typically:
A dense graph has many possible edges present.
This distinction affects which representation is sensible.
Sparse
Adjacency list often better.
Dense
Adjacency matrix may be convenient.
73. Maximum undirected edges
For a simple graph with:
vertices:
because each pair can have at most one edge.
74. Maximum directed edges
For a simple directed graph without self-loops:
each ordered pair of distinct vertices can be an edge.
So:
because direction distinguishes:
from:
Common mistake: BFS always gives unique order
No.
BFS guarantees increasing distance layers, but the ordering within a layer may depend on adjacency ordering.
Common mistake: DFS finds shortest paths
Not generally.
DFS may go down a long branch before discovering a much shorter route.
For shortest paths in an unweighted graph, think:
Common mistake: graph cycle means repeated vertex in traversal
A traversal can encounter a repeated vertex conceptually because the graph has multiple incoming routes, but visited-state handling prevents processing it repeatedly.
Cycle is a structural property of the graph, not simply "I saw something twice in my notes."
Common mistake: DAG means no undirected cycle
A DAG specifically means:
no directed cycles.
The underlying undirected structure may contain an undirected cycle while the edge directions prevent a directed cycle.
Example:
textA → B ↓ ↓ C → D
Underlying undirected edges form a square-like structure, but there may be no directed route returning to its start.
Common mistake: degree in directed graph
Do not use a single ambiguous degree if the question distinguishes direction.
Track:
and:
Common mistake: path length
Path:
contains:
- 4 vertices
- 3 edges
Path length is usually:
not 4.
81. BFS pseudocode
A clean conceptual version:
textBFS(G, s): mark s visited enqueue s while queue not empty: v = dequeue for each neighbor u of v: if u not visited: mark u visited parent[u] = v enqueue u
Key structure:
82. DFS pseudocode
Recursive version:
textDFS(G, v): mark v visited for each neighbor u of v: if u not visited: parent[u] = v DFS(G, u)
Key structure:
83. A useful comparison mental model
Think of exploring a building.
BFS
Check:
- every room 1 door away
- then every room 2 doors away
- then 3 doors away
Good for shortest number of doors.
DFS
Pick one corridor and keep walking until it ends.
Then backtrack.
Good for fully exploring branches.
84. Full graph-analysis example
Suppose:
textA — B — D | | C — E
Vertices:
Edges:
So:
and:
Degrees:
Sum:
And:
Handshaking lemma confirmed.
85. Is this graph a tree?
It has:
vertices and:
edges.
It is connected and has no cycles.
Therefore:
86. BFS from A
Possible BFS:
Layers:
So shortest distance from A to E:
87. DFS from A
Depending on neighbor ordering, one valid DFS:
Another could differ.
Again:
traversal order depends on tie-breaking.
88. Week 10 formula/fact sheet
Graph
G=(V,E)Handshaking lemma
v∑deg(v)=2∣E∣Complete undirected graph
∣E∣=2n(n−1)BFS complexity
O(V+E)DFS complexity
O(V+E)Tree
For a tree:
DAG
directed + no directed cycle89. Week 10 conceptual map
textGraph G=(V,E) │ ├── vertices ├── edges ├── degree ├── paths ├── cycles └── connectivity │ ▼ Representation ├── adjacency matrix └── adjacency list │ ▼ Traversal ├── BFS → queue → layers → shortest unweighted path └── DFS → stack → depth → backtracking │ ▼ Structure ├── components ├── trees └── DAGs └── dependency ordering
90. What you should actually master
By the end of Week 10, you should be able to:
- Define:
- graph
- vertex
- edge.
- Distinguish directed and undirected graphs.
- Compute vertex degree.
- Compute in-degree and out-degree.
- Apply the handshaking lemma.
- Identify paths and cycles.
- Determine connectivity/components.
- Construct/read adjacency matrices.
- Construct/read adjacency lists.
- Explain BFS.
- Trace BFS manually.
- Explain why BFS gives shortest paths in unweighted graphs.
- Explain DFS.
- Trace DFS manually.
- Distinguish queue-based BFS from stack/recursive DFS.
- Recognize a tree.
- Use:
appropriately for trees.
18. Recognize a DAG.
19. Understand dependency/topological-order intuition.
20. Know BFS/DFS traversal complexity:
If those are comfortable, Week 10 is under control.
Quick Recall & Flashcards
Test your active recall before proceeding to practice problems. Format:
Question :: Answer.- Handshaking Lemma for undirected graph G=(V,E) :: ∑v∈Vdeg(v)=2∣E∣
- Maximum number of edges in simple undirected graph with n vertices :: (2n)=2n(n−1)
- Maximum number of directed edges in simple digraph with n vertices :: n(n−1)
- Breadth-First Search (BFS) primary data structure :: Queue (FIFO) — finds shortest paths in unweighted graphs
- Depth-First Search (DFS) primary data structure :: Stack (LIFO) or recursion
- Number of edges in a tree with n vertices :: n−1
- DAG stands for :: Directed Acyclic Graph
- A directed graph has a topological sort if and only if :: It contains no directed cycles (it is a DAG)
Practice & Self-Check
Attempt these diagnostic questions to verify your operational understanding.
1
Question 1
An undirected graph has 6 vertices, each of degree 3. How many edges does the graph have?
NAT
3 Unit Assessment
2
Question 2
Which data structure is fundamentally used to implement Breadth-First Search (BFS)?
MCQ
3 Unit Assessment
A. Stack (LIFO)
B. Queue (FIFO)
C. Priority Queue
D. Binary Search Tree