Beyond Syllabus - 1
Beyond Syllabus - 1
EXPERIMENT NO-1
AIM:
Write a program to compute shortest path for one source –one destination using Bellman ford
Algorithm.
SOFTWARE REQUIRED:
Turbo C
THEORY:
The Shortest Path problem involves finding a path from a source vertex to a destination vertex
which has the least length among all such paths.
Algorithm
Following are the detailed steps.
1) This step initializes distances from source to all vertices as infinite and distance to source
itself as 0. Create an array dist[] of size |V| with all values as infinite except dist[src] where src is
source vertex.
2) This step calculates shortest distances. Do following |V|-1 times where |V| is the number of
vertices in given graph.
a) Do following for each edge u-v
If dist[v] >dist[u] + weight of edge uv, then update dist[v]
dist[v] = dist[u] + weight of edge uv
3) This step reports if there is a negative weight cycle in graph.
Do following for each edge u-v.
If dist[v] >dist[u] + weight of edge uv, then “Graph contains negative weight cycle”
The idea of step 3 is, step 2 guarantees shortest distances if graph doesn’t contain negative
weight cycle. If we iterate through all edges one more time and get a shorter path for any vertex,
then there is a negative weight cycle.
#include<iostream>
#include <list>
using namespace std;
public:
Graph(int V); // Constructor
void addEdge(int u, int v);
void printAllPaths(int s, int d);
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
}
else // If current vertex is not destination
{
// Recur for all the vertices adjacent to current vertex
list<int>::iterator i;
for (i = adj[u].begin(); i != adj[u].end(); ++i)
if (!visited[*i])
printAllPathsUtil(*i, d, visited, path, path_index);
}
// Driver program
int main()
{
// Create a graph given in the above diagram
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(0, 3);
g.addEdge(2, 0);
g.addEdge(2, 1);
g.addEdge(1, 3);
int s = 2, d = 3;
cout<< "Following are all different paths from " << s
<< " to " << d <<endl;
g.printAllPaths(s, d);
return 0;
}
OUTPUT:
Following are all different paths from 2 to 3
2013
203
213
CONCLUSION:
The Shortest Path problem involves finding a path from a source vertex to a destination vertex
which has the least length among all such paths between source and destination. In computer
network, there are many shortest path algorithms. If edges weight is negative then we use
Bellman Ford Algorithm Otherwise Dijkstra’s Shortest Path Algorithm. In this algorithm edges
weight may be positive or negative. The weight and shortest path is calculated repeatedly
between one source and all destination nodes (nodes except source node) until it is achieved.
DISCUSSION: