-
Notifications
You must be signed in to change notification settings - Fork 0
Dijkstra
krishanthan4 edited this page Dec 16, 2025
·
1 revision
Implement Dijkstra's algorithm to find the shortest path from a source vertex to all other vertices in a weighted graph with non-negative edge weights.
Dijkstra's algorithm is a greedy algorithm that finds the shortest path from a source vertex to all other vertices in a weighted graph. It works by iteratively selecting the vertex with the minimum distance and updating its neighbors.
- Time Complexity: O((V + E) log V) with min heap
- Space Complexity: O(V)
- Requirement: Non-negative edge weights
- Strategy: Greedy approach
- Use Case: Single-source shortest path
- Initialize distances: 0 for source, ∞ for others
- Use a priority queue (min heap) to track vertices by distance
- While queue is not empty:
- Extract vertex with minimum distance
- For each neighbor, try to relax the edge
- If new distance is shorter, update and add to queue
- Repeat until all vertices are processed
Relaxation: Updating the shortest distance to a vertex
if (dist[u] + weight(u,v) < dist[v]):
dist[v] = dist[u] + weight(u,v)
parent[v] = u
Implement the following methods in Dijkstra.java:
-
shortestPath(Graph graph, int source)- Find shortest distances -
getPath(Graph graph, int source, int dest)- Reconstruct path
- Simple graph with few vertices
- Graph with multiple paths (ensure shortest is found)
- Source equals destination
- Unreachable vertices
- Graph with all equal weights
- Large graph performance
- Use PriorityQueue<int[]> where int[]{vertex, distance}
- Use HashMap to store distances
- Use another HashMap to store parent pointers for path reconstruction
- Mark vertices as visited or use distance checks
- For path reconstruction: backtrack from destination using parents
function Dijkstra(graph, source):
dist[source] = 0
for each vertex v in graph:
if v != source:
dist[v] = INFINITY
pq = PriorityQueue()
pq.add((source, 0))
while pq is not empty:
(u, current_dist) = pq.extractMin()
if current_dist > dist[u]:
continue
for each neighbor v of u:
alt = dist[u] + weight(u, v)
if alt < dist[v]:
dist[v] = alt
parent[v] = u
pq.add((v, alt))
return dist
Graph:
A --1-- B
| |
4 2
| |
C --1-- D
Starting from A:
Step 1: dist[A]=0, visit A, update B(1), C(4)
Step 2: visit B, update D(3)
Step 3: visit D, update C(3)
Step 4: visit C
Final: A(0), B(1), C(3), D(3)
- GPS navigation (shortest route)
- Network routing protocols
- Social network (shortest connection)
- Flight itinerary planning
- Computer networks (packet routing)
- Resource allocation
- Need to always process vertex with minimum distance
- PriorityQueue gives O(log V) for insert/extract
- Alternative: linear search would be O(V²)
| Aspect | Dijkstra | Bellman-Ford |
|---|---|---|
| Weights | Non-negative only | Any weights |
| Time | O((V+E) log V) | O(VE) |
| Negative cycles | No | Detects |
| Approach | Greedy | Dynamic Prog |
- How would you modify this for negative weights? (Hint: Bellman-Ford)
- How would you find k shortest paths?
- Can you optimize for sparse graphs?
- How would you handle dynamic graphs (edges added/removed)?
- Not handling unreachable vertices
- Using wrong data structure (not priority queue)
- Forgetting to check if new distance is actually shorter
- Processing vertices multiple times
- Not initializing distances correctly
- Bidirectional search: Search from both ends
- A algorithm*: Add heuristic for goal-directed search
- Lazy deletion: Don't remove from PQ, check on extraction
- Fibonacci heap: Improve to O(E + V log V) theoretically
- Source equals destination (distance = 0)
- Unreachable vertices (distance = ∞)
- Single vertex graph
- Self-loops
- Multiple edges between vertices
function reconstructPath(parent, dest):
path = []
current = dest
while current is not null:
path.add(current)
current = parent[current]
reverse(path)
return path
- Bellman-Ford (handles negative weights)
- Floyd-Warshall (all pairs shortest path)
- A* (with heuristic)
- Bidirectional Dijkstra
- Johnson's algorithm
- Network Delay Time
- Cheapest Flights Within K Stops
- Path With Minimum Effort
- Minimum Cost to Reach Destination
- Shortest Path with Alternating Colors