Skip to main content

Graph

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(V2)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+VlogV)O(\vert E \vert + \vert V \vert \log \vert V \vert)See aboveIntuitiveNo negative cycle detection
Bellman-FordO(VE)O(\vert V \vert \vert E \vert)O(V)O(\vert V \vert)RobustSlow
Floyd-WarshallO(V3)O(\vert V \vert ^ 3)O(V2)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(ElogV)O(\vert E \vert \log \vert V \vert)
      • with Fibonacci heap: O(E+VlogV)O(\vert E \vert + \vert V \vert \log \vert V \vert)
    • Dense graph, use Adjacency Matrix: O(V2)O(\vert V \vert ^ 2)
  • Kruskal: Greedy algorithm, select the cheapest edge that connects at least one new vertex
AlgorithmTime Complexity
Borůvka'sO(ElogV)O(\vert E \vert \log \vert V \vert)
PrimSee above
KruskalO(ElogV)O(\vert E \vert \log \vert V \vert)
tip

See optimization for special cases on Wikipedia