Skip to content
Chethan Yadav_
Data Structures & Algorithms

DSA/Lesson 8 of 11/6 min read

Graphs

Graph representations, BFS and DFS, topological sort, shortest paths with Dijkstra and Bellman-Ford, MST and union-find.


On this page

Graph

A graph G = (V, E) is a set of vertices and edges.

KindMeaning
Directed vs undirectedEdges have a direction or not
Weighted vs unweightedEdges carry a cost or not
Cyclic vs acyclicContains a cycle or not (DAG = directed acyclic graph)
ConnectedPath between every pair of vertices (undirected)
Strongly connectedPath both ways between every pair (directed)
Dense vs sparseE close to V^2 vs close to V

Representations

Adjacency List

For each vertex, a list of neighbors. Space O(V + E). Best for sparse graphs, which is most real graphs.

from collections import defaultdict
graph = defaultdict(list)
for u, v in edges:
    graph[u].append(v)
    graph[v].append(u)  # undirected

Adjacency Matrix

A V x V grid where M[u][v] is 1 or the weight. Space O(V^2), edge check O(1). Good for dense graphs and Floyd-Warshall.

ListMatrix
SpaceO(V + E)O(V^2)
Check edge u-vO(deg u)O(1)
Iterate neighborsO(deg u)O(V)

Breadth-First Search (BFS)

BFS explores level by level with a queue. In an unweighted graph it finds the shortest path (fewest edges).

from collections import deque
 
def bfs(graph, src):
    dist = {src: 0}
    q = deque([src])
    while q:
        u = q.popleft()
        for v in graph[u]:
            if v not in dist:
                dist[v] = dist[u] + 1
                q.append(v)
    return dist

O(V + E) time. Mark nodes visited when enqueued, not when dequeued, or nodes get added many times.

Uses: shortest path in grids, word ladder, rotting oranges (multi-source BFS), level-wise problems.

Depth-First Search (DFS)

DFS goes as deep as possible, then backtracks. Recursion or an explicit stack. O(V + E).

def dfs(u, graph, visited):
    visited.add(u)
    for v in graph[u]:
        if v not in visited:
            dfs(v, graph, visited)

Uses: connected components, cycle detection, path finding, flood fill (number of islands), topological sort, strongly connected components (Kosaraju, Tarjan), bridges and articulation points.

Cycle detection

  • Undirected: during DFS, a visited neighbor that is not the parent means a cycle. Or use union-find.
  • Directed: use three colors (white, gray, black). Reaching a gray node (on the current recursion stack) means a back edge, so a cycle.

Bipartite Graph

Vertices split into two sets with every edge crossing between them. Check by 2-coloring with BFS or DFS; a conflict means not bipartite. A graph is bipartite if and only if it has no odd-length cycle.

Topological Sort

A linear order of a DAG where every edge u to v puts u before v. Used for build systems, course schedules, task dependencies.

Kahn's algorithm (BFS)

from collections import deque
 
def topo_sort(n, edges):
    graph = [[] for _ in range(n)]
    indeg = [0] * n
    for u, v in edges:
        graph[u].append(v)
        indeg[v] += 1
    q = deque(i for i in range(n) if indeg[i] == 0)
    order = []
    while q:
        u = q.popleft()
        order.append(u)
        for v in graph[u]:
            indeg[v] -= 1
            if indeg[v] == 0:
                q.append(v)
    return order if len(order) == n else []  # empty means a cycle

DFS variant: push a node onto a list after visiting all descendants, then reverse the list.

Shortest paths

AlgorithmGraphTimeNotes
BFSUnweightedO(V + E)Fewest edges
0-1 BFSWeights 0 or 1O(V + E)Deque
DijkstraNon-negative weightsO((V + E) log V)Min-heap
Bellman-FordNegative weights allowedO(V * E)Detects negative cycles
Floyd-WarshallAll pairsO(V^3)DP over intermediate vertex

Dijkstra's Algorithm

Greedy: always expand the closest unfinished vertex.

import heapq
 
def dijkstra(graph, src):
    dist = {src: 0}
    pq = [(0, src)]
    while pq:
        d, u = heapq.heappop(pq)
        if d > dist.get(u, float("inf")):
            continue  # stale entry
        for v, w in graph[u]:
            nd = d + w
            if nd < dist.get(v, float("inf")):
                dist[v] = nd
                heapq.heappush(pq, (nd, v))
    return dist

Pitfall: Dijkstra gives wrong answers with negative edge weights, because a finalized node could later get a shorter path.

Bellman-Ford

Relax every edge V - 1 times. If an edge can still be relaxed in round V, there is a negative cycle. Used in distance-vector routing (routing).

Floyd-Warshall

dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) for every k. Simple triple loop, all pairs.

Minimum Spanning Tree

A subset of edges connecting all vertices with minimum total weight and no cycles (V - 1 edges).

  • Kruskal: sort edges by weight; add an edge if it joins two different components (union-find). O(E log E).
  • Prim: grow from a start vertex, always adding the cheapest edge leaving the tree (min-heap). O(E log V).

Kruskal is easier for sparse edge lists; Prim suits dense graphs.

Union-Find

Disjoint Set Union tracks which component each element belongs to.

parent = list(range(n))
rank = [0] * n
 
def find(x):
    if parent[x] != x:
        parent[x] = find(parent[x])  # path compression
    return parent[x]
 
def union(a, b):
    ra, rb = find(a), find(b)
    if ra == rb:
        return False
    if rank[ra] < rank[rb]:
        ra, rb = rb, ra
    parent[rb] = ra
    if rank[ra] == rank[rb]:
        rank[ra] += 1
    return True

With path compression and union by rank, each operation is nearly O(1) (inverse Ackermann). Uses: Kruskal, number of connected components, redundant connection, accounts merge.

Quick revision

  • Adjacency list O(V + E) for sparse graphs; matrix O(V^2) for dense.
  • BFS gives shortest paths in unweighted graphs; mark visited on enqueue.
  • DFS for components, cycles, topological order; gray node means directed cycle.
  • Topological sort only on DAGs; Kahn's algorithm detects cycles when output is short.
  • Dijkstra needs non-negative weights; Bellman-Ford handles negatives and detects negative cycles.
  • MST: Kruskal (sort + union-find) or Prim (heap).
  • Union-find with path compression and union by rank is nearly constant time.