🧠 Graph Theory for Competitive Programming
In competitive programming, few topics are as powerful—and sometimes intimidating—as graph theory. Whether it’s shortest paths, connected components, or cycles, graphs appear everywhere from Google Maps to dependency resolution.
In this article, we’ll explore the essential graph concepts, common problems, and Go (Golang) code snippets to help you handle any graph-based challenge on coding platforms like Codeforces, LeetCode, or AtCoder.
🕸️ What Is a Graph?
A graph is a collection of nodes (vertices) and edges (connections between nodes). It can be:
- Directed or Undirected
- Weighted or Unweighted
- Connected or Disconnected
- Cyclic or Acyclic
A simple undirected graph looks like:
graph TD
A(1) -- 2 ↔ 1 --> B(2)
B -- 3 ↔ 2 --> C(3)
C -- 4 ↔ 3 --> D(4)
D -- 1 ↔ 4 --> A
In Go, we typically represent graphs using an adjacency list.
|
|
🔍 DFS and BFS – Graph Traversal
Use DFS
for problems involving backtracking, connected components, and cycle detection.
Use BFS
for shortest paths in unweighted graphs or level-order traversal
Depth-First Search (DFS)
|
|
Breadth-First Search (BFS)
|
|
🔗 Connected Components
In an undirected graph, you can find connected components by running DFS from each unvisited node.
|
|
⛓️ Cycle Detection (Undirected Graph)
DFS with parent tracking:
|
|
📐 Topological Sort (Directed Acyclic Graph)
Used in task scheduling or course dependency problems.
|
|
🛣️ Dijkstra’s Algorithm (Shortest Path)
Used in weighted graphs with non-negative edges.
|
|
Hint
You’ll need a priority queue with container/heap.
🎯 Key Problem Patterns
Problem | Technique |
---|---|
Find if a graph is connected | DFS / BFS |
Shortest path (unweighted graph) | BFS |
Shortest path (weighted graph) | Dijkstra’s |
All-pairs shortest paths | Floyd-Warshall |
Topological sort | DFS / Kahn’s Algo |
Cycle detection (undirected graph) | DFS + parent |
Bipartite graph check | BFS + coloring |
🧠 Final Thoughts
Graph problems may seem tough at first, but they become second nature with practice. Whether it’s mapping networks, detecting cycles, or optimizing routes, graph theory is a core skill that unlocks deep algorithmic power.
✍️ Practice Tip:
Solve 10–15 problems covering DFS
, BFS
, topological sort
, and shortest path
. Then go deeper into Union-Find
, Bridges
, and Articulation Points
.
🚀 Follow me on norbix.dev for more insights on Go, system design, and engineering wisdom.