Program to solve all pairs shortest path problem using dynamic programming

// program to solve all pairs shortest path problem using dynamic programming

#include<iostream.h>
#include<conio.h>

class graph
{
	int cost[20][20],n,a[20][20];

	public:
		void setdata();
		void getdata();
		void path();
};

void graph::setdata()
{
	int i,j,k;

	cout<<"\nEnter number of nodes: ";
	cin>>n;

	cout<<"\nEnter Cost matrix (32767 for infinity): ";

	for(i=1;i<=n;i++)
	{
		cout<<"\nEnter "<<i<<"row :";
		for(j=1;j<=n;j++)
			cin>>cost[i][j];
	}
}

void graph::getdata()
{
	int i,j;

	for(i=1;i<=n;i++)
	{
		for(j=1;j<=n;j++)
			cout<<a[i][j]<<"\t";
		cout<<"\n\n";
	}
}

void graph::path()
{
	int i,j,k,l;

	for(i=1;i<=n;i++)
		for(j=1;j<=n;j++)
			a[i][j]=cost[i][j];

	for(k=1;k<=n;k++)
		for(i=1;i<=n;i++)
			for(j=1;j<=n;j++)
			{
				l=a[i][k]+a[k][j];
				a[i][j]=(a[i][j]>l)?l:a[i][j];
			}
}

void main()
{
	graph g;
	clrscr();

	g.setdata();
	g.path();

	cout<<"\nMatrix with Shortest paths is: \n\n";
	g.getdata();

	getch();
}
Chitra
Chitra

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in