Graph Algorithms and BFS/DFS
# CHAPTER 15
Graph Algorithms and BFS/DFS
1. Chapter Introduction
Trees are a subset of Graphs. While Trees flow strictly downwards from a root, Graphs are chaotic. Any node can point to any other node, creating cycles, bidirectional pathways, and isolated islands. If a FAANG interview question involves a social network ("Friend recommendations"), a flight map, or dependencies ("Course Prerequisites"), you are dealing with a Graph. This chapter covers Graph representation, BFS/DFS traversal, and Topological Sorting.2. Representing a Graph in Memory
Before you can traverse a Graph, you must convert the prompt into a usable data structure. *Prompt:* Node 1 is connected to Node 2 and 3. Node 2 is connected to 4. 1. Adjacency Matrix: A 2D boolean array wherematrix[1][2] = True.
*Problem:* Wastes massive amounts of O(N^2) Space if connections are sparse.
2. Adjacency List (The Industry Standard): A Hash Map where the Key is the Node, and the Value is a List of its neighbors.
*Always build an Adjacency List as step #1 in a Graph interview.*
3. Graph Traversal: The Cycle Problem
If you run a standard Tree DFS on a Graph, you will likely hit an infinite loop. (Node A points to Node B, Node B points to Node A). *The Solution:* Thevisited Hash Set. You must keep track of every node you have seen. If you arrive at a node that is already in the visited set, you instantly return.
4. Graph DFS (Depth-First Search)
DFS plunges as deep as possible down a path. Use DFS for finding if a path exists between two nodes, or for counting "Islands."*Example: Number of Islands (LeetCode 200)* *Prompt:* Given an M x N 2D grid map of '1's (land) and '0's (water), count the number of islands. *Logic:* Iterate through every cell. If you find a '1', increment the island count. Then, launch a recursive DFS to "sink" (change to '0' or add to visited set) all connected '1's horizontally and vertically.
5. Graph BFS (Breadth-First Search)
BFS explores outward in expanding rings (level-by-level). CRITICAL RULE: BFS is the ONLY algorithm you should use to find the Shortest Path in an unweighted graph. (e.g., "What is the fewest number of flights from NY to Tokyo?"). *Implementation:* Iterative, using a Queue.6. Pattern: Topological Sorting
*Prompt:* Course Schedule (LeetCode 207). You must take Course A before Course B. Can you finish all courses? This is a Directed Acyclic Graph (DAG) dependency problem. *Algorithm (Kahn's Algorithm - Indegree):*- 1. Calculate the "Indegree" (number of incoming arrows) for every node.
-
2.
Put all nodes with Indegree
0(courses with no prerequisites) into a Queue.
- 3. While the Queue is not empty:
- Pop a node (take the course).
- "Remove" its outgoing arrows by reducing the Indegree of its neighbors by 1.
-
If a neighbor's Indegree hits
0, add it to the Queue!
- 4. If you processed all nodes, success. If not, a cycle exists (Course A requires B, and B requires A).
7. Real-World Scenario: Dijkstra's Algorithm
BFS finds the shortest path if all edges have a weight of 1. But what if flights have different costs? NY to Chicago is $100. Chicago to Tokyo is $500. Dijkstra's Algorithm finds the shortest path in a weighted graph. *How it works:* It is identical to BFS, but instead of using a standard Queue, it uses a Min-Heap (Priority Queue). It always explores the cheapest available path first.8. Mini Project: Build an Adjacency List
Given a list of edges representing friendships:edges = [[0,1], [0,2], [1,2], [2,3]].
Write code to build an undirected Adjacency List.
9. Common Mistakes
- Forgetting Directed vs. Undirected: If the prompt says "A is connected to B", you must ask if it's a two-way street. If it is undirected, your Adjacency List must append B to A's list, AND append A to B's list.
-
Forgetting the Visited Set: Trying to traverse a graph without a
visitedset will almost always result in an infinite loop and a crashed interview.
10. Best Practices
-
Time/Space Complexity: Building an Adjacency List takes
O(V + E)whereVis Vertices (nodes) andEis Edges. Standard BFS/DFS traversal is also O(V + E) Time, because you visit every node once, and iterate through every edge once.
11. Exercises
- 1. Why is BFS better than DFS for finding the "Shortest Path" in a maze?
-
2.
Trace Kahn's Algorithm (Indegrees) for
Course 1 -> Course 2 -> Course 3.
12. MCQs
What is the standard and most space-efficient data structure used to represent a Graph in a coding interview?
When traversing a Graph, what mechanism is absolutely mandatory to prevent infinite loops (Cycles)?
If an interview prompt asks for the "Shortest Path" or "Fewest Steps" through an unweighted network, which algorithm MUST you use?
In the "Number of Islands" problem (2D Grid), what is the role of the DFS function when it finds a piece of land ('1')?
What specific class of problems requires "Topological Sorting"?
In Kahn's Algorithm for Topological Sorting, what defines the "Indegree" of a node?
If Kahn's Algorithm finishes but the processed elements do NOT equal the total number of nodes in the graph, what does that signify?
How does Dijkstra's Algorithm differ from standard BFS?
What is the standard Time Complexity for traversing a Graph using BFS or DFS?
What is a critical step when converting a list of edges into an Adjacency List for an "Undirected" graph?
14. Interview Questions
-
Q: "There are
ncities connected by some number of flights. You are given an arrayflightswhereflights[i] = [fromi, toi, price_i]. Find the cheapest price fromsrctodstwith up tokstops." (LeetCode 787).
15. FAQs
- Q: Are graph problems considered "Hard"?
16. Summary
Graphs represent interconnected data. Always start by translating the raw input into an Adjacency List. If searching for the shortest path, implement BFS iteratively using a Queue. If searching for existence or sinking components, use a recursive DFS. Never forget thevisited set to prevent infinite loops. Master Kahn's Indegree algorithm for dependency problems, and understand that Time Complexity is evaluated as O(V + E).