Shortest patha algorithms explained
Shortest patha algorithms explained
Introduction
The shortest path problem is a fundamental problem in graph theory and computer science. It
involves finding the shortest possible path between two vertices (nodes) in a weighted or unweighted
graph. Shortest path algorithms are widely used in navigation systems, computer networks, robotics,
artificial intelligence, and social networks.
Python Implementation
python
CopyEdit
import heapq
return distances
print(dijkstra(graph, 'A'))
Python Implementation
python
CopyEdit
def bellman_ford(graph, start):
distances = {node: float('inf') for node in graph}
distances[start] = 0
return distances
graph = {
'A': {'B': 1, 'C': 4},
'B': {'C': 2, 'D': 5},
'C': {'D': -3},
'D': {}
}
print(bellman_ford(graph, 'A'))
Python Implementation
python
CopyEdit
def floyd_warshall(graph):
nodes = list(graph.keys())
dist = {node: {neighbor: float('inf') for neighbor in nodes} for node in nodes}
for k in nodes:
for i in nodes:
for j in nodes:
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
return dist
graph = {
'A': {'B': 3, 'C': 8},
'B': {'A': 3, 'C': 2},
'C': {'A': 8, 'B': 2}
}
print(floyd_warshall(graph))