Graph
Vertices, edges, types, representation, BFS, DFS, and key graph algorithms
Introduction to Graphs
A Graph is a non-linear data structure consisting of Vertices (Nodes) and Edges (Connections). Graphs model relationships between objects and are one of the most widely used structures in computer science.
Graphs appear everywhere in real-world applications:
- Social Networks (users as vertices, friendships as edges)
- Google Maps and GPS navigation (cities as vertices, roads as edges)
- Computer Networks (routers as vertices, links as edges)
- Flight routes, recommendation systems, and web page links
Formally, a graph G is defined as:
G = (V, E)
V = Set of Vertices = {A, B, C, D}
E = Set of Edges = {(A,B), (A,C), (B,D), (C,D)}
This gives a graph that looks like:
A
/ \
B C
\ /
D
Basic Terminology
Understanding these terms is essential before diving into graph algorithms.
Vertex (Node)
An individual element in the graph. Example: A, B, C, D.
Edge
A connection between two vertices. Example: A ā B.
Degree
The number of edges connected to a vertex. In a directed graph, in-degree counts incoming edges and out-degree counts outgoing edges.
A
/ \
B C
Degree(A) = 2
Adjacent Vertices
Vertices directly connected by an edge. In the example above, A and B are adjacent.
Path
A sequence of vertices connected by edges. Example: A ā B ā D.
Cycle
A path that starts and ends at the same vertex. Example: A ā B ā C ā A.
Connected vs Disconnected
A graph is connected if every vertex is reachable from every other vertex. Otherwise it is disconnected.
Connected: A --- B --- C
Disconnected: A --- B C --- D
Types of Graphs
Graphs come in several forms, each suited to different problems.
Undirected Graph
Edges have no direction ā travel is possible in both directions between any connected pair of vertices.
A ----- B (A can reach B, B can reach A)
Directed Graph (Digraph)
Edges have a direction ā an edge A ā B means you can go from A to B but not necessarily back.
A ā B ā C
ā |
| ā
E ā D ā-
Weighted Graph
Each edge carries a weight (cost, distance, time). Used in shortest path and MST algorithms.
A --5-- B
| |
2 4
| |
C --1-- D
Unweighted Graph
All edges are considered equal ā no weights. BFS finds shortest paths in terms of edge count.
Cyclic vs Acyclic
A cyclic graph contains at least one cycle. An acyclic graph has no cycles.
Directed Acyclic Graph (DAG)
A directed graph with no cycles. Essential for topological sorting, build systems, and dependency resolution.
A
| \
v v
B C
\ |
v
D
Complete Graph
Every vertex is connected to every other vertex. For n vertices, the number of edges is:
Edges = n(n ā 1) / 2
Bipartite Graph
Vertices are split into two disjoint sets where edges only go between the sets (never within a set). Used in matching problems and recommendation systems.
Students Subjects
Alice ------- Math
Alice ------- Science
Bob --------- Science
Graph Representation
There are two standard ways to store a graph in memory. The right choice depends on whether the graph is sparse (few edges) or dense (many edges).
Adjacency Matrix
A 2D boolean (or weight) matrix where matrix[i][j] = 1 if there is an edge from vertex i to vertex j.
Graph:
A
/ \
B---C
Matrix:
A B C
A 0 1 1
B 1 0 1
C 1 1 0
int[][] graph = {
{0, 1, 1},
{1, 0, 1},
{1, 1, 0}
};
Advantages: Simple to implement. Edge lookup is O(1).
Disadvantages: Space complexity is O(V²) ā wasteful for sparse graphs.
Adjacency List
Each vertex stores a list of its neighbors. Much more memory-efficient for sparse graphs.
Graph:
A --- B
|
C
Adjacency List:
A ā [B, C]
B ā [A]
C ā [A]
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i < V; i++) {
graph.add(new ArrayList<>());
}
// Add edges for undirected graph
graph.get(0).add(1); // A - B
graph.get(0).add(2); // A - C
graph.get(1).add(0); // B - A
graph.get(2).add(0); // C - A
Advantages: Space complexity O(V + E) ā efficient for sparse graphs.
Disadvantages: Checking if an edge exists may require O(degree) traversal.
Matrix vs List
| Feature | Adjacency Matrix | Adjacency List |
|---|---|---|
| Space | O(V²) | O(V + E) |
| Edge lookup | O(1) | O(degree) |
| Add edge | O(1) | O(1) |
| Iterate neighbors | O(V) | O(degree) |
| Best for sparse graphs | Poor | Excellent |
| Best for dense graphs | Good | Good |
Graph Traversal
Traversal means visiting every reachable vertex in the graph. There are two fundamental strategies:
- BFS ā Breadth First Search (level by level)
- DFS ā Depth First Search (as deep as possible first)
Both have time complexity O(V + E) and space complexity O(V).
Breadth First Search (BFS)
BFS visits all vertices at distance 1 from the source first, then distance 2, and so on. It uses a queue (FIFO) to track which vertices to visit next.
Graph:
A
/ \
B C
/
D
BFS from A: A ā B ā C ā D
Algorithm steps:
- Start at the source vertex, mark it visited, enqueue it.
- Dequeue the front vertex and process it.
- Enqueue all unvisited neighbors and mark them visited.
- Repeat until the queue is empty.
public void bfs(int start) {
Queue<Integer> queue = new LinkedList<>();
boolean[] visited = new boolean[V];
visited[start] = true;
queue.offer(start);
while (!queue.isEmpty()) {
int node = queue.poll();
System.out.print(node + " ");
for (int neighbor : graph.get(node)) {
if (!visited[neighbor]) {
visited[neighbor] = true;
queue.offer(neighbor);
}
}
}
}
| Complexity | Value |
|---|---|
| Time | O(V + E) |
| Space | O(V) |
BFS guarantees the shortest path (in terms of edge count) in an unweighted graph.
Depth First Search (DFS)
DFS explores as far as possible along each branch before backtracking. It uses a stack ā either explicit or via the call stack through recursion.
Graph:
A
/ \
B C
/
D
DFS from A: A ā B ā D ā C
Recursive implementation:
public void dfs(int node, boolean[] visited) {
visited[node] = true;
System.out.print(node + " ");
for (int neighbor : graph.get(node)) {
if (!visited[neighbor]) {
dfs(neighbor, visited);
}
}
}
Iterative implementation using an explicit stack:
public void dfsIterative(int start) {
Stack<Integer> stack = new Stack<>();
boolean[] visited = new boolean[V];
stack.push(start);
while (!stack.isEmpty()) {
int node = stack.pop();
if (!visited[node]) {
visited[node] = true;
System.out.print(node + " ");
for (int neighbor : graph.get(node)) {
if (!visited[neighbor]) {
stack.push(neighbor);
}
}
}
}
}
| Complexity | Value |
|---|---|
| Time | O(V + E) |
| Space | O(V) |
BFS vs DFS
| Feature | BFS | DFS |
|---|---|---|
| Data structure | Queue | Stack / Recursion |
| Traversal order | Level by level | Depth first |
| Shortest path (unweighted) | Yes | No |
| Memory usage | Higher (wide graphs) | Lower (deep graphs) |
| Cycle detection | Yes | Yes |
| Topological sort | No | Yes |
| Connected components | Yes | Yes |
Topological Sorting
Topological sorting produces a linear ordering of vertices in a Directed Acyclic Graph (DAG) such that for every directed edge u ā v, vertex u comes before v.
DAG:
A ā C
B ā C
C ā D
Valid topological orders:
A B C D
B A C D
DFS-based approach:
public void topoSort(int node,
boolean[] visited,
Stack<Integer> stack) {
visited[node] = true;
for (int neighbor : graph.get(node)) {
if (!visited[neighbor]) {
topoSort(neighbor, visited, stack);
}
}
stack.push(node); // push after all descendants
}
Applications: course scheduling, build systems, dependency resolution, Git commit ordering.
Time Complexity: O(V + E)
Minimum Spanning Tree
A Spanning Tree of a graph includes all vertices connected with the minimum number of edges (exactly V ā 1 edges, no cycles). The Minimum Spanning Tree (MST) is the spanning tree with the lowest total edge weight.
Prim's Algorithm
Builds the MST by greedily adding the cheapest edge that connects a new vertex to the growing tree. Uses a priority queue.
Time Complexity: O((V + E) log V)
Kruskal's Algorithm
Sorts all edges by weight and adds them one by one, skipping any edge that would create a cycle (detected using Union-Find / Disjoint Set Union).
Time Complexity: O(E log E)
MST applications: road network design, network cable routing, electrical grid planning.
Shortest Path Algorithms
Finding the shortest path between vertices is one of the most important graph problems.
Dijkstra's Algorithm
Works with non-negative edge weights. Uses a min-heap priority queue to always expand the cheapest unvisited vertex.
public int[] dijkstra(int src) {
int[] dist = new int[V];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[src] = 0;
PriorityQueue<int[]> pq =
new PriorityQueue<>(Comparator.comparingInt(a -> a[1]));
pq.offer(new int[]{src, 0});
while (!pq.isEmpty()) {
int[] curr = pq.poll();
int node = curr[0], d = curr[1];
if (d > dist[node]) continue;
for (int[] edge : graph.get(node)) {
int neighbor = edge[0], weight = edge[1];
if (dist[node] + weight < dist[neighbor]) {
dist[neighbor] = dist[node] + weight;
pq.offer(new int[]{neighbor, dist[neighbor]});
}
}
}
return dist;
}
Time Complexity: O((V + E) log V)
Applications: GPS navigation, route planning, network packet routing.
Bellman-Ford Algorithm
Handles graphs with negative edge weights. Relaxes all edges V ā 1 times. Can also detect negative weight cycles.
Time Complexity: O(V Ć E)
Floyd-Warshall Algorithm
Finds shortest paths between all pairs of vertices using dynamic programming. Works with negative weights (but not negative cycles).
Time Complexity: O(V³)
| Algorithm | Negative Weights | Single Source | All Pairs | Complexity |
|---|---|---|---|---|
| Dijkstra | No | Yes | No | O((V+E) log V) |
| Bellman-Ford | Yes | Yes | No | O(VE) |
| Floyd-Warshall | Yes | No | Yes | O(V³) |
Cycle Detection
Detecting whether a graph contains a cycle is important in dependency checking, deadlock detection, and validating DAGs.
Undirected Graph
Use DFS with parent tracking, or Union-Find (Disjoint Set Union). If a visited neighbor is not the parent, a cycle exists.
public boolean hasCycleUndirected(int node,
int parent,
boolean[] visited) {
visited[node] = true;
for (int neighbor : graph.get(node)) {
if (!visited[neighbor]) {
if (hasCycleUndirected(neighbor, node, visited))
return true;
} else if (neighbor != parent) {
return true; // back edge found ā cycle
}
}
return false;
}
Directed Graph
Use DFS with a recursion stack. If a visited vertex is already in the current recursion stack, a cycle exists.
public boolean hasCycleDirected(int node,
boolean[] visited,
boolean[] recStack) {
visited[node] = true;
recStack[node] = true;
for (int neighbor : graph.get(node)) {
if (!visited[neighbor]) {
if (hasCycleDirected(neighbor, visited, recStack))
return true;
} else if (recStack[neighbor]) {
return true; // back edge ā cycle
}
}
recStack[node] = false;
return false;
}
Complexity Summary
| Algorithm | Time Complexity | Space |
|---|---|---|
| BFS | O(V + E) | O(V) |
| DFS | O(V + E) | O(V) |
| Topological Sort | O(V + E) | O(V) |
| Dijkstra | O((V + E) log V) | O(V) |
| Bellman-Ford | O(V Ć E) | O(V) |
| Floyd-Warshall | O(V³) | O(V²) |
| Prim's MST | O((V + E) log V) | O(V) |
| Kruskal's MST | O(E log E) | O(V) |
| Cycle Detection | O(V + E) | O(V) |
Applications of Graphs
Graphs power some of the most important systems in computing:
Social Networks
Users are vertices, friendships or follows are edges. Used to find mutual friends, shortest social distance, and community detection.
Maps and Navigation
Cities are vertices, roads are weighted edges. Dijkstra's and A* algorithms find optimal routes.
Internet and Networking
Routers are vertices, connections are edges. Routing protocols use shortest path algorithms to forward packets efficiently.
Compiler Design
Dependency graphs determine compilation order. Topological sort ensures each module is compiled after its dependencies.
Operating Systems
Resource Allocation Graphs detect deadlocks. A cycle in this graph means a deadlock exists.
Recommendation Systems
Bipartite graphs model users and items. Graph traversal identifies what similar users liked.
Artificial Intelligence
State space graphs represent all possible states of a problem. BFS and DFS power search algorithms like A* pathfinding.
Common Interview Questions
Easy
- What is a Graph? How is it different from a Tree?
- What is the degree of a vertex?
- What is the difference between directed and undirected graphs?
- What is a cycle in a graph?
Medium
- Implement BFS and DFS for an adjacency list.
- Detect a cycle in an undirected graph.
- Detect a cycle in a directed graph.
- Count connected components in a graph.
- Find the number of islands (LeetCode 200).
- Perform topological sort on a DAG.
Hard
- Dijkstra's shortest path algorithm.
- Bellman-Ford with negative weight detection.
- Kruskal's or Prim's MST algorithm.
- Strongly Connected Components (Kosaraju / Tarjan).
- Shortest path in a grid with obstacles.
- Word Ladder problem (BFS on implicit graph).
Revision Summary
A Graph is a non-linear data structure made of vertices and edges used to model relationships between objects.
Key Types
- Directed / Undirected
- Weighted / Unweighted
- Cyclic / Acyclic
- DAG (Directed Acyclic Graph)
- Complete and Bipartite graphs
Representation
- Adjacency Matrix ā O(V²) space, O(1) edge lookup
- Adjacency List ā O(V + E) space, preferred for sparse graphs
Core Traversals
- BFS ā Queue ā shortest path in unweighted graphs
- DFS ā Stack/Recursion ā cycle detection, topological sort
Must-Know Algorithms
- BFS and DFS
- Topological Sort (Kahn's BFS or DFS-based)
- Dijkstra (non-negative weights)
- Bellman-Ford (negative weights)
- Floyd-Warshall (all-pairs shortest path)
- Prim and Kruskal (Minimum Spanning Tree)
- Cycle Detection (DFS with parent / recursion stack)
Graphs are among the most important topics in DSA. They model real-world problems in networking, navigation, scheduling, AI, and social systems ā and appear frequently in coding interviews at every level.