Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Design, develop, and run a program in any language to implement the Bellman-Ford
algorithm and determine its performance.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LabPrograms;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
TestBellmanAlgo();
}
private static void TestBellmanAlgo()
{
int[,] dmat=new int[20,20];
Node[] rt = new Node[10];
int n,i,j;
int t = 0;
for (int p = 0; p < rt.Length; p++)
rt[p].Init(10);
Console.WriteLine("\nEnter the number of nodes : ");
n = int.Parse(Console.ReadLine());
Console.WriteLine("\nEnter the cost matrix :\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
t = int.Parse(Console.ReadLine());
dmat[i,j]=t;
dmat[i,i]=0;
rt[i].dist[j]=dmat[i,j];
rt[i].from[j]=j;
}
BellmanFordAlgo algo = new BellmanFordAlgo();
algo.Do(ref rt, ref dmat, n);
for (i = 0; i < n; i++)
{
string st="\n\nState value for router {0} is \n";
st=string.Format(st,i+1);
Console.WriteLine(st);
for (j = 0; j < n; j++)
{
System;
System.Collections.Generic;
System.Linq;
System.Text;
namespace LabPrograms
{
public struct Node
{
public int[] dist;
public int[] from;
public void Init(int count)
{
dist = new int[count];
from = new int[count];
}
}
public class BellmanFordAlgo
{
public void Do(ref Node[] rt,ref int[,] dmat, int n)
{
int count = 0;
do
{
count = 0;
for(var i=0;i<n;i++)
for(var j=0;j<n;j++)
for(var k=0;k<n;k++)
if(rt[i].dist[j]>dmat[i,k]+rt[k].dist[j])
{
rt[i].dist[j]=rt[i].dist[k]+rt[k].dist[j];
rt[i].from[j]=k;
count++;
}
}while(count!=0);
}
}
}
Output:
0 3 5 99
3 0 99 1
5 4 0
99 1 2