|
| 1 | +""" |
| 2 | +Author : Robin Singh |
| 3 | +Implementation of Bellman Ford Algorithm(Dynamic Programming) |
| 4 | +Bellman Ford algorithm helps us find the shortest path from a vertex to all other vertices of a weighted graph. |
| 5 | +It is similar to Dijkstra's algorithm but it can work with graphs in which edges can have negative weights. |
| 6 | +
|
| 7 | +Time Complexity : Best Case = O(E) |
| 8 | + Worst Case = Average Case = O(VE) |
| 9 | +
|
| 10 | +""" |
| 11 | + |
| 12 | + |
| 13 | +def bellman_ford_SSS(graph,src): |
| 14 | + dist = dict() |
| 15 | + prev = dict() |
| 16 | + for node in graph: |
| 17 | + dist[node] =float('Inf') |
| 18 | + prev[node] = None |
| 19 | + dist[src] = 0 |
| 20 | + |
| 21 | + for _ in range(len(graph)-1): |
| 22 | + for node in graph: |
| 23 | + for neighbour in graph[node]: |
| 24 | + if dist[neighbour] > dist[node]+graph[node][neighbour]: |
| 25 | + dist[neighbour] = dist[node]+graph[node][neighbour] |
| 26 | + prev[neighbour] = node |
| 27 | + |
| 28 | + for node in graph: |
| 29 | + for neighbour in graph[node]: |
| 30 | + assert dist[neighbour] <= dist[node]+graph[node][neighbour],"Error,Graph Has Negative Weight Cycle" |
| 31 | + |
| 32 | + |
| 33 | + return dist,prev |
| 34 | + |
| 35 | +if __name__ == '__main__': |
| 36 | + #Case 1 |
| 37 | + graph = { |
| 38 | + 'a':{'b':6,'c':4,'d':5}, |
| 39 | + 'b':{'e':-1}, |
| 40 | + 'c':{'e':3,'b':-2}, |
| 41 | + 'd':{'c':-2,'f':-1}, |
| 42 | + 'e':{'f':3}, |
| 43 | + 'f':{} |
| 44 | + } |
| 45 | + |
| 46 | + distance,prev = bellman_ford_SSS(graph,'a') |
| 47 | + print("Distances From point A") |
| 48 | + print(distance) |
| 49 | + |
| 50 | + print("Predecssor Vertices") |
| 51 | + print(prev) |
| 52 | + |
| 53 | + |
| 54 | + #graph with Negative Weight Cycle |
| 55 | + #Case 2 |
| 56 | + graph = { |
| 57 | + 'a':{'b':4,'c':5}, |
| 58 | + 'b':{'d':7}, |
| 59 | + 'c':{'b':7}, |
| 60 | + 'd':{'c':-15}#change value from -15 to -14 to make graph Postive Weight Cycle |
| 61 | + } |
| 62 | + distance,prev = bellman_ford_SSS(graph, 'a') |
| 63 | + print("") |
| 64 | + print("Distances From point A") |
| 65 | + print(distance) |
| 66 | + |
| 67 | + print("Predecssor Vertices") |
| 68 | + print(prev) |
| 69 | + |
0 commit comments