Skip to main content

Graph Fundamentals

DFS vs BFS Graph Traversal

The Mental Model

Graphs model relationships. Cities connected by roads, friends in a social network, dependencies between tasks—all graphs. Mastering graphs means learning to see problems as nodes and edges, then applying the right traversal or algorithm. Analogy: A graph is a map. Nodes are locations; edges are roads connecting them. BFS is like a flood spreading outward from a point—it reaches all nearby locations first, then farther ones. DFS is like exploring a maze by always going deeper into one corridor until you hit a dead end, then backtracking. Both visit every reachable location, but the order is different, and that order matters for the problem you are solving.
Pattern Recognition Signals:
  • “Connected components” → DFS/BFS + Union-Find
  • “Shortest path” → BFS (unweighted) or Dijkstra (weighted)
  • “Cycle detection” → DFS with colors
  • “Topological ordering” → Kahn’s algorithm or DFS
  • “Bipartite check” → BFS/DFS coloring

Graph Representations

Adjacency List (Most Common in CP)

Edge List (For Kruskal’s MST)

Adjacency Matrix (Dense Graphs, Floyd-Warshall)


DFS explores as deep as possible before backtracking. It is the foundation for many graph algorithms: cycle detection, topological sort, SCC, bridges, and more. Time Complexity: O(V + E) — every node is visited once, and every edge is examined once. Space Complexity: O(V) for the visited array and recursion stack (stack depth = longest path from root).

Iterative DFS (Avoids Stack Overflow)


BFS explores all neighbors before going deeper. BFS finds shortest path in unweighted graphs.

BFS on Grid


Pattern 1: Connected Components

Problem: Count connected components or check if two nodes are connected.
Codeforces Problems:

Pattern 2: Cycle Detection

In Undirected Graph

In Directed Graph (Using Colors)

Analogy: Think of DFS as exploring a cave system. White nodes are unexplored rooms. Gray nodes are rooms you are currently inside (on your current path from the entrance). Black nodes are rooms you fully explored and left. If you find a passage to a gray room, you have found a cycle — you can walk in a circle back to where you are. Why three colors instead of two? In directed graphs, visiting an already-visited node does not always mean a cycle. If the node is black (fully processed), the edge goes to a separate branch — no cycle. Only a back edge to a gray (in-progress) node forms a cycle.

Pattern 3: Topological Sort

Problem: Order nodes so all edges go from earlier to later.

Kahn’s Algorithm (BFS)

Analogy: Think of university course prerequisites. You can only take a course when all its prerequisites are done. Kahn’s algorithm starts with courses that have no prerequisites (in-degree 0), “takes” them, and reduces the prerequisite count for dependent courses. When a course’s count drops to zero, it becomes available. If you process all courses this way and some remain, there is a circular dependency — a cycle.

DFS Approach

Codeforces Problems:

Pattern 4: Bipartite Check

Problem: Can we 2-color the graph such that no edge connects same colors?
Key Insight: A graph is bipartite if and only if it has no odd-length cycles. This is because in a 2-coloring, every edge alternates colors, and a cycle of odd length would require a color to be adjacent to itself.
Contest tip: Many problems do not explicitly say “bipartite.” Look for signals like “divide into two groups such that all edges go between groups” or “2-colorable.” Also, any tree is bipartite (trees have no cycles at all).

Pattern 5: Flood Fill

Problem: Find connected regions in a grid (like paint bucket tool).

Common Mistakes

Mistake 1: 0 vs 1 Indexing Be consistent. In CP, 1-indexing is common for graphs.
Mistake 2: Forgetting to Check All Components Not all nodes may be reachable from node 1:
Mistake 3: Stack Overflow in DFS For graphs with 10^5+ nodes, use iterative DFS or increase stack size.
Mistake 4: Revisiting in BFS Mark visited when pushing to queue, not when popping. If you mark on pop, a node can be pushed multiple times by different neighbors, wasting time and potentially causing O(V^2) behavior on dense graphs.

Practice Problems

Beginner (1000-1200)

Intermediate (1200-1500)

Advanced (1500-1700)


Key Takeaways

DFS for Exploration

Use DFS for connectivity, cycles, and backtracking problems.

BFS for Shortest

BFS gives shortest path in unweighted graphs.

Adjacency List

Default representation in CP. O(V + E) space.

Color for State

Track visited/processing/done states for cycle detection.

Next Up

Chapter 14: Shortest Paths

Master Dijkstra, Bellman-Ford, and Floyd-Warshall for weighted shortest paths.