0% found this document useful (0 votes)
11 views

62837Lecture 04 (b) Dijkstras Algorithm

Dijkstra's algorithm is a graph search method for finding the shortest path from a starting node to all other nodes in a graph with non-negative edge weights, commonly used in navigation and network routing. The algorithm initializes distances, iteratively updates them based on the shortest known paths, and can reconstruct the path if needed. Key properties include requiring non-negative weights and being efficient for sparse graphs, but it cannot handle negative weights and may use high memory for large graphs.

Uploaded by

saad aslam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

62837Lecture 04 (b) Dijkstras Algorithm

Dijkstra's algorithm is a graph search method for finding the shortest path from a starting node to all other nodes in a graph with non-negative edge weights, commonly used in navigation and network routing. The algorithm initializes distances, iteratively updates them based on the shortest known paths, and can reconstruct the path if needed. Key properties include requiring non-negative weights and being efficient for sparse graphs, but it cannot handle negative weights and may use high memory for large graphs.

Uploaded by

saad aslam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Dijkstra's Algorithm

Definition:
Dijkstra's algorithm is a graph search algorithm used to find the shortest path from a starting
node to all other nodes in a graph with non-negative edge weights. It is widely used in network
routing and mapping applications.

How It Works
1. Initialization:
o Start by assigning a distance of 0 to the source node and infinity to all other
nodes.
o Keep a priority queue to store the nodes with their current distances.
2. Iterative Updates:
o Pick the node with the smallest known distance (the closest unvisited node).
o For each of its neighbors, calculate the tentative distance through the current
node.
o If this new distance is smaller than the previously known distance, update it.
3. Repeat:
o Continue until all nodes have been visited or the shortest path to the target node is
found.
4. Reconstruct Path (Optional):
o Use the predecessors recorded during the updates to reconstruct the shortest path.

Steps with Example


Problem:
Find the shortest path from node A to all other nodes in the following graph:
Graph:
A ---1--- B
\ /\
4 2 6
\ / \
C ---3--- D
Weights:
• A to B: 1
• A to C: 4
• B to C: 2
• B to D: 6
• C to D: 3

Step-by-Step Solution
1. Initialization:
o Start at node A.
o Set distances:
Distance: A = 0, B = ∞, C = ∞, D = ∞
o Unvisited nodes: {A, B, C, D}
2. Iteration 1:
o Pick the node with the smallest distance: A (distance = 0).
o Update neighbors:
▪ B: New distance = 0 + 1 = 1.
▪ C: New distance = 0 + 4 = 4.
o Update table:
Distance: A = 0, B = 1, C = 4, D = ∞
o Unvisited nodes: {B, C, D}
3. Iteration 2:
o Pick the node with the smallest distance: B (distance = 1).
o Update neighbors:
▪ C: New distance = 1 + 2 = 3 (better than 4, so update).
▪ D: New distance = 1 + 6 = 7.
o Update table:
Distance: A = 0, B = 1, C = 3, D = 7
o Unvisited nodes: {C, D}
4. Iteration 3:
o Pick the node with the smallest distance: C (distance = 3).
o Update neighbors:
▪ D: New distance = 3 + 3 = 6 (better than 7, so update).
o Update table:
Distance: A = 0, B = 1, C = 3, D = 6
o Unvisited nodes: {D}
5. Iteration 4:
o Pick the node with the smallest distance: D (distance = 6).
o No neighbors to update.
6. Final Table:
Shortest Distances: A = 0, B = 1, C = 3, D = 6

Shortest Paths
• A to A: 0 (itself).
• A to B: A → B (distance = 1).
• A to C: A → B → C (distance = 3).
• A to D: A → B → C → D (distance = 6).

Applications of Dijkstra's Algorithm


1. Navigation Systems:
o GPS uses it to calculate the shortest driving route.
2. Network Routing:
o Determines the least-cost path in packet-switched networks.
3. Transport Systems:
o Identifies the shortest routes in rail or road networks.
4. Game AI:
o Finds optimal paths for characters in games.

Key Properties
• Non-Negative Weights: Dijkstra's algorithm requires non-negative edge weights.
• Efficiency: Works efficiently for sparse graphs and small-to-medium graph sizes.
Limitations
• Cannot Handle Negative Weights: Use Bellman-Ford algorithm for graphs with
negative weights.
• High Memory Usage: Not suitable for very large graphs.
This example and explanation should clarify the concept and workings of Dijkstra's Algorith

Implementation of Dijkstra's Algorithm in Python


Implementation of Dijkstra's Algorithm in Python, which is used to find the shortest path from
a source node to all other nodes in a weighted graph.
import heapq # Priority queue for efficient selection of the smallest distance

def dijkstra(graph, start):


"""
Dijkstra's algorithm for finding the shortest paths from the start node to all other nodes in a
graph.

graph: Dictionary where keys are nodes and values are dictionaries of neighbors with edge
weights.
start: The starting node.

Returns:
- A dictionary with the shortest distance from the start node to each node.
- A dictionary with the shortest path (via predecessors) to reconstruct the route.
"""
# Priority queue to hold (distance, node)
priority_queue = []
heapq.heappush(priority_queue, (0, start))

# Distance table: Distance from start to each node


distances = {node: float('inf') for node in graph}
distances[start] = 0

# Predecessor table to reconstruct paths


predecessors = {node: None for node in graph}

while priority_queue:
current_distance, current_node = heapq.heappop(priority_queue)

# Skip if we have already found a better way


if current_distance > distances[current_node]:
continue

# Update distances to neighbors


for neighbor, weight in graph[current_node].items():
distance = current_distance + weight

# If found a shorter path, update


if distance < distances[neighbor]:
distances[neighbor] = distance
predecessors[neighbor] = current_node
heapq.heappush(priority_queue, (distance, neighbor))

return distances, predecessors


def reconstruct_path(predecessors, start, goal):
"""
Reconstructs the shortest path from start to goal using the predecessor table.

predecessors: A dictionary with each node's predecessor.


start: Starting node.
goal: Goal node.

Returns:
- A list representing the shortest path from start to goal.
"""
path = []
current = goal
while current is not None:
path.append(current)
current = predecessors[current]
path.reverse()
return path

Example Graph and Usage


# Example weighted graph
graph = {
'A': {'B': 1, 'C': 4},
'B': {'A': 1, 'C': 2, 'D': 6},
'C': {'A': 4, 'B': 2, 'D': 3},
'D': {'B': 6, 'C': 3}
}
# Run Dijkstra's algorithm
start_node = 'A'
distances, predecessors = dijkstra(graph, start_node)

# Print shortest distances from the start node


print("Shortest distances:", distances)

# Reconstruct and print shortest path from start to a specific node


goal_node = 'D'
shortest_path = reconstruct_path(predecessors, start_node, goal_node)
print(f"Shortest path from {start_node} to {goal_node}:", shortest_path)

Output Example
For the graph above:
Shortest distances: {'A': 0, 'B': 1, 'C': 3, 'D': 6}
Shortest path from A to D: ['A', 'B', 'C', 'D']

Explanation
1. Graph Representation: The graph is represented as a dictionary where each node points
to its neighbors along with the edge weights.
2. Priority Queue: The algorithm uses a priority queue (via heapq) to efficiently select the
node with the smallest distance.
3. Distance Table: Keeps track of the shortest distance from the start node to every other
node.
4. Predecessor Table: Records the previous node for each node to reconstruct the shortest
path.
5. Reconstruct Path: Using the predecessor table, the shortest path is reconstructed.
This implementation ensures efficient computation and works well for both small and medium-
sized graphs. Let me know if you need further explanations!

You might also like