Shortest Path Algorithm: Definition, How It Works, and Examples
shortest path algorithm finds the quickest or least costly route between two points in a network or graph. It helps determine the minimum distance or cost to travel from a start point to a destination.How It Works
Imagine you want to find the fastest way to get from your home to a friend's house using roads. The shortest path algorithm looks at all possible routes and picks the one with the least distance or travel time. It works by exploring connected points (called nodes) and measuring the cost to move between them.
One common way it works is by starting at the beginning point and checking all nearby points, then moving step-by-step to the next closest point until it reaches the destination. It keeps track of the shortest known distance to each point and updates this information as it finds better routes.
This process is like planning a trip using a map app that suggests the quickest route by comparing all possible roads and traffic conditions.
Example
This example uses Dijkstra's algorithm, a popular shortest path method, to find the shortest distance from a start node to all other nodes in a graph.
import heapq def dijkstra(graph, start): distances = {node: float('inf') for node in graph} distances[start] = 0 priority_queue = [(0, start)] while priority_queue: current_distance, current_node = heapq.heappop(priority_queue) if current_distance > distances[current_node]: continue for neighbor, weight in graph[current_node].items(): distance = current_distance + weight if distance < distances[neighbor]: distances[neighbor] = distance heapq.heappush(priority_queue, (distance, neighbor)) return distances # Graph represented as adjacency list with edge weights graph = { 'A': {'B': 5, 'C': 1}, 'B': {'A': 5, 'C': 2, 'D': 1}, 'C': {'A': 1, 'B': 2, 'D': 4, 'E': 8}, 'D': {'B': 1, 'C': 4, 'E': 3, 'F': 6}, 'E': {'C': 8, 'D': 3}, 'F': {'D': 6} } start_node = 'A' shortest_distances = dijkstra(graph, start_node) print(shortest_distances)
When to Use
Shortest path algorithms are useful whenever you need to find the best route or minimum cost path in a network. This includes GPS navigation to find the fastest driving route, internet data routing to send information efficiently, and even in games to move characters along the best path.
They are also used in logistics to optimize delivery routes, in social networks to find connections between people, and in robotics for path planning.
Key Points
- Shortest path algorithms find the minimum distance or cost between points in a graph.
- Dijkstra's algorithm is a common method that works well with positive edge weights.
- These algorithms are widely used in navigation, networking, logistics, and more.
- Graphs represent points as nodes and connections as edges with weights.