Loading...
Graphs, traversal, and shortest paths
Section 3 of 4
Learn how to find the shortest paths in weighted graphs using classic algorithms
Purpose: Single-source shortest paths
Constraint: Non-negative edge weights
Time: O((V + E) log V) with min-heap
Space: O(V)
| Algorithm | Type | Time Complexity | Space | Negative Weights | Best For |
|---|---|---|---|---|---|
| Dijkstra's | Single-source | O((V+E) log V) | O(V) | No | GPS, routing |
| Bellman-Ford | Single-source | O(V × E) | O(V) | Yes | Currency exchange |
| Floyd-Warshall | All-pairs | O(V³) | O(V²) | Yes | Dense graphs |
function dijkstra(graph, source):
// Initialize distances and visited set
distances = {}
visited = set()
pq = MinHeap() // Priority queue
// Set all distances to infinity, source to 0
for each vertex v in graph:
distances[v] = INFINITY
distances[source] = 0
pq.insert(source, 0)
while pq is not empty:
current = pq.extractMin()
if current in visited:
continue
visited.add(current)
// Relax all neighbors
for each neighbor of current:
weight = graph.getWeight(current, neighbor)
newDistance = distances[current] + weight
if newDistance < distances[neighbor]:
distances[neighbor] = newDistance
pq.insert(neighbor, newDistance)
return distancesFinding shortest routes between locations considering road weights (distance, time, traffic).
Internet packet routing protocols like OSPF use shortest path algorithms.
Finding degrees of separation and suggesting connections between users.