Multi-Stage Graphs using Dynamic Programming technique.

 

Algorithm:

Algorithm BGraph(G, k, n, p){

bcost[l]:=0.0;

for j:=2 to n do     {

Let r be such that (r, j) is an edge of G and bcost[r] + c[r,j] is minimum; bcost[j]:=bcost[r]+c[r,j];

d[j]:=r;     } p[l]:1; p[k]:=n;

for j:=k— 1 to 2 do p[j]:=d[p[j+1]];}

Source Code:

def shortestDist(graph): global INF

dist = [0] * N path = [None] * N dist[N - 1] = 0

for i in range(N - 2, -1, -1): dist[i] = INF

for j in range(N):

if graph[i][j] == INF: continue

if dist[i] > graph[i][j] + dist[j]: dist[i] = graph[i][j] + dist[j] path[i] = j

shortest_path = [0]

node = 0

while node != N-1:

node = path[node] shortest_path.append(node)

return dist[0], shortest_path

N = 8

INF = 999999999999

graph = [[INF, 1, 2, 5, INF, INF, INF, INF],

[INF, INF, INF, INF, 4, 11, INF, INF],

[INF, INF, INF, INF, 9, 5, 16, INF],

[INF, INF, INF, INF, INF, INF, 2, INF],

[INF, INF, INF, INF, INF, INF, INF, 18],

[INF, INF, INF, INF, INF, INF, INF, 13],

[INF, INF, INF, INF, INF, INF, INF, 2]]

shortest_dist, shortest_path = shortestDist(graph) print("Shortest distance:", shortest_dist) print("Shortest path:", shortest_path[::-1])

Comments

Popular posts from this blog

2. Create 3 private networks namely N1, N2 and N3, Send the data from N1 to N2. If the packets are transferring from N3, it shouldn't accept the packets. Accordingly develop the security features.Create 3 private networks namely N1, N2 and N3, Send the data from N1 to N2. If the packets are transferring from N3, it shouldn't accept the packets. Accordingly develop the security features.

Kruskal algorithm using greedy technique.