Skip to main content
LeetCode Prep
CHAPTER 15 Beginner

Graph Algorithms and BFS/DFS

Updated: May 18, 2026
5 min read

# 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 where matrix[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.
python
123456
adj_list = {
    1: [2, 3],
    2: [4],
    3: [],
    4: []
}

*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:* The visited 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. 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.

python
12345678
def dfs(r, c):
    if r < 0 or c < 0 or r >= ROWS or c >= COLS or grid[r][c] == &#039;0':
        return
    grid[r][c] = &#039;0' # Mark as visited (sink the island)
    dfs(r - 1, c) # Up
    dfs(r + 1, c) # Down
    dfs(r, c - 1) # Left
    dfs(r, c + 1) # Right
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.
python
1234567891011121314151617
from collections import deque

def shortestPath_BFS(start, target, adj_list):
    queue = deque([(start, 0)]) # Queue stores (Node, Distance)
    visited = set([start])
    
    while queue:
        node, dist = queue.popleft()
        
        if node == target:
            return dist # Found shortest path!
            
        for neighbor in adj_list[node]:
            if neighbor not in visited:
                visited.add(neighbor)
                queue.append((neighbor, dist + 1))
    return -1

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. 1. Calculate the "Indegree" (number of incoming arrows) for every node.
  1. 2. Put all nodes with Indegree 0 (courses with no prerequisites) into a Queue.
  1. 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!
  1. 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.
python
1234
adj = {i: [] for i in range(4)}
for n1, n2 in edges:
    adj[n1].append(n2)
    adj[n2].append(n1) # Because it is undirected (two-way street)

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 visited set 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) where V is Vertices (nodes) and E is 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. 1. Why is BFS better than DFS for finding the "Shortest Path" in a maze?
  1. 2. Trace Kahn's Algorithm (Indegrees) for Course 1 -> Course 2 -> Course 3.

12. MCQs

Question 1

What is the standard and most space-efficient data structure used to represent a Graph in a coding interview?

Question 2

When traversing a Graph, what mechanism is absolutely mandatory to prevent infinite loops (Cycles)?

Question 3

If an interview prompt asks for the "Shortest Path" or "Fewest Steps" through an unweighted network, which algorithm MUST you use?

Question 4

In the "Number of Islands" problem (2D Grid), what is the role of the DFS function when it finds a piece of land ('1')?

Question 5

What specific class of problems requires "Topological Sorting"?

Question 6

In Kahn's Algorithm for Topological Sorting, what defines the "Indegree" of a node?

Question 7

If Kahn's Algorithm finishes but the processed elements do NOT equal the total number of nodes in the graph, what does that signify?

Question 8

How does Dijkstra's Algorithm differ from standard BFS?

Question 9

What is the standard Time Complexity for traversing a Graph using BFS or DFS?

Question 10

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 n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, price_i]. Find the cheapest price from src to dst with up to k stops." (LeetCode 787).

15. FAQs

  • Q: Are graph problems considered "Hard"?
A: They look terrifying, but they are actually highly procedural. Once you memorize the 5-line template for building an Adjacency List and the standard BFS Queue loop, you can solve almost any medium Graph problem.

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 the visited set to prevent infinite loops. Master Kahn's Indegree algorithm for dependency problems, and understand that Time Complexity is evaluated as O(V + E).

17. Next Chapter Recommendation

We have looked at highly complex algorithms like DP and Graphs. But sometimes, the optimal solution doesn't require maintaining state or exploring all paths; sometimes, making the locally optimal choice at every step is enough. In Chapter 16: Greedy Algorithms and Intervals, we will learn how to schedule meetings and merge overlapping arrays.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·