DSA — Dijkstra's Algorithm
What is Dijkstra's Algorithm?
Finds the shortest path from a source to all vertices in a weighted graph.
import heapq
def dijkstra(graph, start):
distances = {vertex: float('infinity') for vertex in graph}
distances[start] = 0
previous = {vertex: None for vertex in graph}
pq = [(0, start)]
while pq:
current_dist, current = heapq.heappop(pq)
if current_dist > distances[current]:
continue
for neighbor, weight in graph[current].items():
distance = current_dist + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
previous[neighbor] = current
heapq.heappush(pq, (distance, neighbor))
return distances, previous
Time Complexity
| Operation | Complexity |
|---|---|
| Using priority queue | O((V + E) log V) |
| Using array | O(V²) |
Applications
- GPS navigation
- Network routing
- Flight scheduling
- Robotics path planning
Mini Practice
- Implement Dijkstra's algorithm
- Find shortest path
- Reconstruct the path
- Handle negative weights (use Bellman-Ford)
Up Next
Continue with Floyd-Warshall — all-pairs shortest path.
Related Topics
Frequently Asked Questions about Dijkstra's Algorithm
What is Dijkstra's Algorithm in DSA?
Dijkstra's Algorithm is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Dijkstra's Algorithm?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Dijkstra's Algorithm.
Why is Dijkstra's Algorithm important in DSA?
Dijkstra's Algorithm is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.