Skip to main content

Graph

Various algorithms for graph problems.

tip

CS Academy's Graph Editor provides simple graph visualization.

Traverse​

AlgorithmTime ComplexitySpace ComplexityNotes
DFSO(∣V∣+∣E∣)O(\vert V \vert + \vert E \vert)O(∣V∣)O(\vert V \vert)Use stack for iteration
BFSO(∣V∣+∣E∣)O(\vert V \vert + \vert E \vert)O(∣V∣)O(\vert V \vert)Use queue for iteration

Shortest Path​

  • Dijkstra: Weighted BFS + Priority Queue iteration
    • Sparse graph, use Adjacency List: O(∣V∣+∣E∣)O(\vert V \vert + \vert E \vert)
    • Dense graph, use Adjacency Matrix: O(∣V∣2)O(\vert V \vert ^ 2)
  • Bellman-Ford: Based on Dijkstra, but checks all edges for each iteration
  • Floyd-Warshall: Bottom-up DP to calculate shortest distances between all pairs
AlgorithmTime ComplexitySpace ComplexityProsCons
DijkstraO(∣E∣+∣V∣log⁡∣V∣)O(\vert E \vert + \vert V \vert \log \vert V \vert)See aboveIntuitiveNo negative cycle detection
Bellman-FordO(∣V∣∣E∣)O(\vert V \vert \vert E \vert)O(∣V∣)O(\vert V \vert)RobustSlow
Floyd-WarshallO(∣V∣3)O(\vert V \vert ^ 3)O(∣V∣2)O(\vert V \vert ^ 2)FastNeed additional steps to construct path
info

Bellman-Ford and Floyd-Warshall can handle negative weights and detect negative cycles, while Dijkstra can not.

Minimum Spanning Tree​

  • Borůvka's: Greedy algorithm, select the cheapest edge for each component
  • Prim: Greedy algorithm, select the cheapest edge that connects exactly one old vertex and one new vertex
    • Sparse graph, use Adjacency List
      • with binary heap: O(∣E∣log⁡∣V∣)O(\vert E \vert \log \vert V \vert)
      • with Fibonacci heap: O(∣E∣+∣V∣log⁡∣V∣)O(\vert E \vert + \vert V \vert \log \vert V \vert)
    • Dense graph, use Adjacency Matrix: O(∣V∣2)O(\vert V \vert ^ 2)
  • Kruskal: Greedy algorithm, select the cheapest edge that connects at least one new vertex
AlgorithmTime Complexity
Borůvka'sO(∣E∣log⁡∣V∣)O(\vert E \vert \log \vert V \vert)
PrimSee above
KruskalO(∣E∣log⁡∣V∣)O(\vert E \vert \log \vert V \vert)
tip

See optimization for special cases on Wikipedia