- In graph theory, there are four major types of problems:
- Searching: We want to find a node, n in the tree
- Minimum spanning tree: We want to find a way to connect all nodes in the cheapest way possible.
- Single source shortest path: We want to find the shortest path from a source node, u to every other node, v in the graph.
- All pairs shortest path: We want to find the shortest path from all nodes to every other nodes in the graph
Searching algorithms
- There are two important search algorithms:
- Depth-first search (DFS)
- Breadth-first search (BFS)
- General differences:
- DFS uses stack while BFS uses queue
- DFS results in a “taller” tree while BFS results in a tree with more branches
- DFS Pseudocode
|
|
- BFS Pseudocode
|
|
Minimum spanning tree
- Minimum spanning tree: Connected and acyclic graph in which the total weight of edges is the smallest
- Two ways to create MST:
- Prim’s algorithm
- Choose vertex
- Maintain one MST during building process
- Kruskal’s algorithm
- Choose edge
- Maintain one or more MST during building process
- Prim’s algorithm
- Prim’s Algorithm Pseudocode
|
|
- Kruskal’s Algorithm Pseudocode
|
|
- Both Prim and Kruskal have time complexity of
O(ElogV)
Single source shortest Path
- Objective is to find shortest path from current node, s to all other nodes
- Two algorithms are available:
- Dijkstra’s
- Cannot handle negative weights
- Better time complexity for positive weights than Bellman-Ford
- Bellman-Ford
- Can handle negative weights
- Dijkstra’s
- Both do not work if there exists a negative cycle
- Dijkstra’s algorithm pseudocode
|
|
- Bellman-Ford algorithm Pseudocode
|
|
- Helper algorithms
|
|
- Time complexity of Dijkstra
- Without max-heap:
O(V^2)
- With max-heap:
O(ElogV)
- Without max-heap:
- Time complexity of Bellman-Ford is
O(VE)
All Pairs Shortest Path
- Objective is for each pair of vertex, u and v, of the graph, find the shortest path between these two nodes
- Two algorithms:
- Johnson’s:
- Complex as heck, but better time complexity
- Floyd-Warshall
- Simple, uses matrices
- Johnson’s:
- Johnson’s algorithm high level overview
- Add a new vertex to the graph and add edge to each existing vertex on the graph
- Apply Bellman-Ford algorithm and normalize the graph to remove all negative-weighted edges
- Remove the extra vertex in step 1 and apply Dijkstra’s on all original vertices.
- Floyd-Warshall algorithm pseudocode
|
|
- Floyd-Warshall time complexity is
O(V^3)
- Johnson’s algorithm time complexity is
O(V^2 log V + VE)