Neural Sync Active
Week 9: Graph Traversal — BFS & DFS
Registry Synced
Week 9: Graph Traversal — BFS & DFS
3847 words
19 min read
2026-09-12
Reading compass
Now · TL;DR
Computational Thinking — Week 9: Graph Traversal — BFS & DFS
IITM’s CT Week 9 moves from representing graphs to systematically exploring them, with Breadth-First Search and Depth-First Search.
TL;DR
A graph may contain many vertices and edges, but simply storing it is not enough. We often need to answer:
- Which vertices can I reach?
- In what order should I explore them?
- Is there a path from A to B?
- How far is a vertex in terms of number of edges?
- Have I already processed this vertex?
Two fundamental traversal algorithms solve these problems:
BFS — Breadth-First Search
Explore level by level:
textstart ↓ all immediate neighbors ↓ neighbors of those neighbors ↓ ...
Uses a:
DFS — Depth-First Search
Explore as far as possible along one branch, then backtrack:
textstart ↓ go deep ↓ go deeper ↓ dead end ↓ backtrack
Uses conceptually:
1. Why graph traversal is needed
Suppose we have:
textA --- B --- D | | C --- E
Knowing the graph exists does not automatically answer:
Which vertices are reachable from A?
An algorithm must systematically inspect the graph.
That is graph traversal.
2. Traversal
Traversal means:
visit vertices according to a systematic rule.
A traversal algorithm generally needs to:
- choose a starting vertex
- visit it
- inspect connected vertices
- remember what has already been visited
- continue until no relevant unvisited vertices remain
3. Why visited is necessary
Consider a cycle:
textA --- B | | D --- C
If the algorithm simply follows neighbors without remembering previous vertices, it could do:
textA → B → C → D → A → B → C → ...
forever.
So we maintain something like:
textvisited
to avoid processing the same vertex repeatedly.
4. Generic traversal idea
Conceptually:
textmark start as discovered while there is something left to explore: choose next vertex examine its neighbors for each neighbor: if neighbor has not been visited: mark/discover it schedule it for later exploration
The major difference between BFS and DFS is:
How do we choose the next vertex?
5. Breadth-First Search
BFS explores a graph breadth first.
Starting from vertex s:
- visit s
- visit all vertices one edge away
- then all vertices two edges away
- then three edges away
- and so on
6. BFS level intuition
Example:
textA / \ B C / \ \ D E F
Starting at:
BFS conceptually explores:
Level 0
ALevel 1
B,CLevel 2
D,E,FSo one possible BFS order is:
assuming neighbors are considered left-to-right/alphabetically as shown.
7. BFS uses a queue
A queue follows:
meaning:
First In, First Out.
Like a line of people:
textfront → A, B, C ← rear
The item inserted earliest is removed first.
8. Why FIFO gives breadth-first behavior
Suppose we start at A.
Queue:
text[A]
Remove A and discover B and C:
text[B, C]
B entered first, so B is processed before C.
When processing B, suppose D and E are discovered:
text[C, D, E]
Notice C, which is still at the same level as B, gets processed before deeper vertices D and E.
That is exactly why BFS proceeds level by level.
9. BFS conceptual pseudocode
A standard form is:
textmark start as visited enqueue start while queue is not empty: v = dequeue for each neighbor u of v: if u is not visited: mark u as visited enqueue u
The exact IITM notation may differ, but this is the core algorithmic structure.
10. BFS trace
Graph:
textA --- B --- D | | C --- E
Assume neighbors are considered alphabetically.
Start at:
Initial state
textQueue = [A] Visited = {A}
Process A.
Neighbors:
Now:
textQueue = [B, C] Visited = {A, B, C}
11. Continue BFS
Process B.
Neighbors may include:
A already visited.
Discover D and E:
textQueue = [C, D, E] Visited = {A, B, C, D, E}
Process C.
Its relevant neighbor E is already discovered.
textQueue = [D, E]
Then process D and E.
Traversal order:
12. Mark when discovered, not too late
A subtle but important pattern:
When an unvisited neighbor is first discovered, mark it immediately.
Conceptually:
textif u not visited: visited[u] = True enqueue(u)
Why?
Suppose two current vertices both point to the same unvisited vertex.
If you wait until dequeue time to mark it, the same vertex might be inserted multiple times.
13. BFS finds shortest paths in unweighted graphs
One of BFS's most important properties:
In an unweighted graph, BFS discovers vertices in increasing number of edges from the source.
Therefore BFS can find shortest path distance measured in number of edges.
14. BFS distances
Suppose:
textA / \ B C | | D --- E
Starting from A:
assuming those are the shortest available routes.
15. Why BFS shortest path works
BFS processes:
before:
before:
and so on.
Therefore the first time a vertex is discovered, BFS has found a minimum-edge route to it.
16. Parent / predecessor
To reconstruct a BFS path, store how each vertex was first reached.
Example:
textparent[B] = A parent[C] = A parent[D] = B
Then if you want the path from A to D:
textD ↑ B ↑ A
reverse it:
17. BFS and weighted graphs
Be careful:
BFS finds shortest paths by edge count.
If edges have different costs:
textA --100-- B A --1-- C --1-- B
BFS may regard direct A→B as one hop.
But weighted cost:
is worse than:
So ordinary BFS is not a general weighted shortest-path algorithm.
18. Depth-First Search
DFS explores one branch as deeply as possible before returning.
Example:
textA / \ B C / \ D E
One DFS starting at A might visit:
then backtrack to B, visit E, then backtrack and eventually visit C.
Possible order:
19. DFS mental model
Think:
keep moving forward while an unvisited neighbor exists.
If you reach a vertex with no unvisited neighbors:
go backward to the most recent unfinished vertex.
This backward movement is backtracking.
20. DFS uses a stack conceptually
A stack follows:
meaning:
Last In, First Out.
Example:
textbottom [A, B, C] top
C was added last, so C is removed first.
This naturally creates deep exploration.
21. Recursion and DFS
DFS can also be expressed recursively:
textDFS(v): mark v visited for each neighbor u of v: if u not visited: DFS(u)
The call stack implicitly remembers where to return after exploring a branch.
22. Recursive DFS intuition
Suppose:
textA → B → D | E
Call:
textDFS(A)
which calls:
textDFS(B)
which calls:
textDFS(D)
When D has nowhere new to go, return to B.
Then B can continue with E.
This is backtracking via recursive calls.
23. Iterative DFS
DFS can also use an explicit stack:
textpush start while stack is not empty: v = pop if v not visited: mark v visited push appropriate neighbors
The exact traversal order depends on the order in which neighbors are pushed.
24. DFS trace example
Graph:
textA --- B --- D | | C --- E
Assume alphabetic preference where possible.
Starting at A:
Choose B:
From B choose D:
D has no new neighbor.
Backtrack to B.
Then choose E:
From E, C may be discovered.
Possible DFS order:
25. BFS vs DFS order is not always unique
The graph alone may not determine a unique traversal order.
Suppose A has neighbors:
If no neighbor-order rule is specified, BFS might process them in several valid orders.
Likewise DFS can choose different branches first.
Therefore:
unless the question specifies an ordering convention.
26. BFS vs DFS comparison
| Feature | BFS | DFS |
|---|---|---|
| Exploration | Level by level | Deep branch first |
| Main structure | Queue | Stack / recursion |
| Principle | FIFO | LIFO |
| Unweighted shortest paths | Yes | Not generally |
| Backtracking | Not central | Central |
| Reachability | Yes | Yes |
27. Both can determine reachability
Suppose the question is simply:
Is C reachable from A?
Either BFS or DFS can search from A.
If C is eventually visited:
If traversal finishes without C:
28. Connected components using traversal
For an undirected graph:
- choose an unvisited vertex
- BFS/DFS from it
- all reached vertices form one connected component
- choose another unvisited vertex
- repeat
So graph traversal can identify connected components.
29. Example
Graph:
textA --- B --- C D --- E F
Run DFS/BFS from A:
Run from next unvisited D:
Then F:
Thus:
30. Traversal using adjacency matrix
Suppose:
To find neighbors of vertex i, scan row i.
For every:
vertex j is adjacent.
So BFS/DFS can operate directly on the Week 8 adjacency-matrix representation.
31. Cost of matrix neighbor search
If there are:
vertices, scanning one adjacency-matrix row checks:
possible neighbors.
Doing this for many vertices may inspect roughly:
matrix entries.
This follows directly from the matrix representation.
32. Traversal with adjacency lists
Another representation could store only actual neighbors:
textA: [B,C] B: [A,D] C: [A] D: [B]
Then traversal only iterates through listed edges.
This is often useful for sparse graphs.
The Week 9 core idea, however, is traversal logic rather than one mandatory storage representation.
33. Visited structure
visited can conceptually be:- Boolean array
- dictionary
- set
- status column
Example:
textvisited[A] = True visited[B] = False
The implementation varies, but the purpose is the same.
34. Vertex states
A useful conceptual refinement is:
Undiscovered
Never encountered.
Discovered
Found and scheduled for processing.
Processed
Its neighbors have been examined.
BFS especially benefits from distinguishing discovery from final processing.
35. Example BFS state table
Graph:
textA --- B | | C --- D
Start A.
| Step | Removed | Queue after | Newly discovered |
|---|---|---|---|
| Start | — | [A] | A |
| 1 | A | [B,C] | B,C |
| 2 | B | [C,D] | D |
| 3 | C | [D] | — |
| 4 | D | [] | — |
One BFS order:
36. Example DFS stack intuition
Same graph:
textA --- B | | C --- D
A possible DFS:
textA ↓ B ↓ D ↓ C
Then all vertices are visited.
Different neighbor ordering could instead produce:
Both may be valid.
37. Cycles and visited
Consider:
textA --- B \ / C
DFS:
At C, A is already visited.
So do not recurse into A again.
This prevents infinite cycling.
BFS uses the same principle.
38. DFS tree
During DFS, the edges used to first discover vertices form a traversal tree.
Example:
textA | B | D
and perhaps another branch:
textB | E
These discovery relationships can be represented using parent pointers.
39. BFS tree
Similarly, first-discovery edges in BFS form a BFS tree rooted at the source.
For unweighted graphs, tree depth corresponds to shortest-path distance from the source.
That is why BFS levels matter.
40. BFS level formula intuition
If vertex u is discovered from v, then:
when u is first reached by BFS.
Start:
This lets BFS compute minimum hop counts.
41. Search can stop early
If the goal is only:
Find whether target T is reachable.
Then when T is discovered/found, the search may stop depending on the exact algorithm.
You do not always need to traverse the whole component.
42. Traversal of disconnected graph
A BFS or DFS from one source only explores vertices reachable from that source.
Example:
textA --- B C --- D
BFS from A visits:
It will never automatically reach:
To traverse the entire graph, start new searches from remaining unvisited vertices.
Common mistake: BFS uses stack
Wrong.
Standard association:
This distinction is fundamental.
Common mistake: DFS finds unweighted shortest path
DFS may find a path, but not necessarily a shortest one.
Example:
textA --- B | | C --- D --- E \--------- E
Depending on exploration order, DFS may take a long route before finding E even though a shorter route exists.
BFS is the standard choice for minimum number of edges.
Common mistake: mark visited only after everything finishes
If marking is delayed too much, the same vertex can be scheduled repeatedly.
For BFS especially, mark when the vertex is first discovered/enqueued.
Common mistake: visit same vertex repeatedly
In a graph with cycles, this may cause:
- duplicated work
- duplicated outputs
- nontermination
Always track visited state unless the particular algorithm intentionally allows revisits.
Common mistake: BFS order assumed unique
If adjacency order is unspecified, several BFS orders can be valid.
What remains invariant is the level structure.
Vertices at smaller distance from the source are discovered before vertices at greater distance.
Common mistake: DFS means "always go left"
No.
"Left" only exists in a particular drawing.
DFS means:
choose an unvisited neighbor and continue deeply.
Which neighbor is chosen depends on the ordering convention.
Common mistake: graph drawing determines algorithm
Two drawings can represent the same graph.
Traversal depends on:
- vertices
- edges
- neighbor ordering
not on arbitrary visual placement on the page.
Common mistake: directed reachability treated as undirected
Graph:
textA ---> B ---> C
From A:
is reachable.
From C:
is not reachable unless reverse paths exist.
Follow arrow directions.
Common mistake: queue and stack behavior reversed
Queue
textenqueue A enqueue B remove → A
FIFO.
Stack
textpush A push B remove → B
LIFO.
This difference produces BFS vs DFS behavior.
52. Queue trace mini-example
Start empty:
text[]
enqueue A:
text[A]
enqueue B:
text[A,B]
dequeue:
textA
remaining:
text[B]
53. Stack trace mini-example
Start:
text[]
push A:
text[A]
push B:
text[A,B]
pop:
textB
remaining:
text[A]
54. BFS worked example
Graph:
textA / \ B C / \ / D E F
Assume alphabetical neighbor ordering.
Start:
textQ = [A] Visited = {A}
Process A:
textQ = [B,C]
Process B:
textQ = [C,D,E]
Process C:
textQ = [D,E,F]
Then D, E, F.
BFS:
55. DFS on the same graph
Starting at A, alphabetical choice:
From B:
D ends → backtrack to B.
Then:
Backtrack to A.
Then:
DFS order:
Same graph, different traversal.
56. BFS vs DFS visual intuition
textBFS: A ↙ ↘ B C ↙ ↘ ↙ ↘ D E F G Process horizontally by layers.
textDFS: A ↓ B ↓ D ↓ ... backtrack ↓ next branch
57. When BFS is naturally useful
BFS fits problems involving:
- minimum number of connections
- shortest path in unweighted graph
- degrees of separation
- nearest reachable target
- level-by-level exploration
Example:
What is the minimum number of flights needed if every flight counts equally?
58. When DFS is naturally useful
DFS fits problems involving:
- exhaustive exploration
- connected components
- cycle-oriented reasoning
- backtracking
- exploring one branch deeply
The exact applications grow in later algorithms, but the traversal pattern itself is foundational.
59. BFS/DFS are algorithmic patterns
Do not memorize them merely as graph-specific recipes.
They represent broader scheduling philosophies:
BFS
Explore possibilities in increasing "distance/depth."
DFS
Commit deeply to one possibility, then backtrack.
These patterns appear elsewhere in computer science and AI search.
60. Relationship to Week 3 procedures
DFS's recursive form is a direct application of procedures calling themselves:
textDFS(v): ... DFS(u)
That is recursion.
Even if recursion is not the main Week 9 syllabus label, the connection explains why procedures matter for graph algorithms.
61. Relationship to Week 4 nested iteration
When traversing via adjacency matrix:
textfor each visited vertex i: inspect columns j
the algorithm repeatedly scans matrix rows.
So graph traversal combines:
- loops
- conditions
- data structures
- state
- matrix representation
Everything from earlier CT weeks starts coming together.
62. Relationship to Week 6 dictionaries
You can conceptually store:
textvisited[vertex] distance[vertex] parent[vertex]
as dictionary-like mappings.
Example:
textdistance[A] = 0 distance[B] = 1
Graph algorithms depend heavily on such per-vertex state.
63. Relationship to Week 8 adjacency matrices
Week 8 answered:
Which vertices are neighbors?
Week 9 answers:
In what order should we repeatedly follow those neighbor relationships?
Thus:
64. Exam-solving workflow
When asked to trace BFS or DFS:
- Write the starting vertex.
- Write the specified neighbor ordering.
- Maintain
visited. - For BFS, maintain the queue after every step.
- For DFS, maintain the recursion/stack path or backtracking state.
- Never revisit an already discovered vertex unless pseudocode explicitly says otherwise.
- Record the traversal order.
- If asked for distances/parents, maintain those separately.
65. BFS trace template
Use:
| Step | Vertex processed | Queue | Newly visited |
|---|---|---|---|
| 0 | — | [start] | start |
| 1 | ... | ... | ... |
| 2 | ... | ... | ... |
This prevents queue-order mistakes.
66. DFS trace template
Use:
| Step | Current vertex | Action | Active path/stack |
|---|---|---|---|
| 1 | A | visit | A |
| 2 | B | go deeper | A→B |
| 3 | D | go deeper | A→B→D |
| 4 | D | dead end/backtrack | A→B |
This makes backtracking explicit.
67. Compact formula / fact sheet
BFS
Queue FIFO level-by-levelFor an unweighted graph:
DFS
Stack / recursion LIFO deep-first + backtrackingBoth require:
68. Week 9 conceptual map
textGRAPH REPRESENTATION ↓ Choose start vertex ↓ Track visited vertices ↓ TRAVERSAL / \ BFS DFS | | Queue Stack/ FIFO Recursion | | Levels Depth | | Shortest Backtrack unweighted distance
69. What you should actually master
By the end of CT Week 9, you should be able to:
- Explain what graph traversal means.
- Explain why a
visitedstructure is necessary. - Describe BFS conceptually.
- Trace a BFS queue.
- Understand FIFO.
- Recognize BFS's level-by-level behavior.
- Compute unweighted shortest-path distance using BFS logic.
- Understand parent/predecessor information.
- Describe DFS conceptually.
- Trace DFS and backtracking.
- Understand LIFO.
- Relate DFS to stacks/recursion.
- Distinguish BFS from DFS.
- Recognize that traversal order can depend on neighbor ordering.
- Use either traversal for reachability.
- Understand how traversal finds connected components.
- Correctly follow edge direction in directed graphs.
- Apply BFS/DFS to adjacency-matrix or neighbor-list representations.
If those are comfortable, Computational Thinking Week 9 is under control.
Quick Recall & Flashcards
Test your active recall before proceeding to practice problems. Format:
Question :: Answer.- Week 9 Diagnostic: Which data structure does Breadth-First Search (BFS) use to manage the discovery frontier? :: Answer: B — BFS processes nodes in level order using a First-In, First-Out Queue.
- Week 9 Diagnostic: Why is a
visitedset or boolean array necessary during graph traversal? :: Answer: B — In graphs with cycles, failing to track visited vertices causes the traversal algorithm to loop infinitely.
Practice & Self-Check
Attempt these diagnostic questions to verify your operational understanding.
1
Question 1
Which data structure does Breadth-First Search (BFS) use to manage the discovery frontier?
MCQ
3 Unit Assessment
A. Stack (LIFO)
B. Queue (FIFO)
C. Binary Search Tree
D. Priority Queue
2
Question 2
Why is a
visited set or boolean array necessary during graph traversal?MCQ
3 Unit Assessment
A. To count the total number of edges
B. To prevent revisiting vertices and getting trapped in infinite loops in cyclic graphs
C. To sort the vertices alphabetically
D. To calculate edge weights