Académique Documents
Professionnel Documents
Culture Documents
{
for (i = 1; i <= n + 1; i++)
{
w[i, n + 1] = 999;
w[n + 1, i] = 0;
}
source = n + 1;
for (i = 1; i <= n + 1; i++)
{
dist[i] = 999;
parent[i] = 999;
}
dist[source] = 0;
parent[source] = -1;
check = johnsonAlgo.BellmanFord(dist, w, parent, n);
if (check == 0)
{
Console.Write("\n No solution exists because of -ve edge
cycle in input graph!!! \n\n");
return;
}
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
{
if ((i != j) && (w[i, j] != 999))
w[i, j] += dist[i] - dist[j];
}
}
// Print the details of the distance b/w source and vertex
for (j = 1; j <= n; j++)
{
int m;
k = 1;
source = j;
for (m = 1; m <= n; N[m++] = 0)
;
D[source] = 0;
N[k++] = source;
johnsonAlgo.Dijikstras(D, N, source, n, w, k);
Console.Write("\n(source s,vertex v): shortest distance from
source {0:D} to vertex v \n", j);
for (i = 1; i <= n; i++)
{
if (johnsonAlgo.InotinN(N,i,n) != 0)
Console.Write("\n (V{0:D},V{1:D}):{2:D} \t", N[1], i, D[i]);
if ((N[i] != source) && (N[i] != 0))
{
System;
System.Collections.Generic;
System.Linq;
System.Text;
namespace LabPrograms
{
public class JohnsonAlgo
{
static int j = 2;
public int BellmanFord(int[] dist,int[,] w ,int[] parent,int n)
{
int i, j;
for (var pass = 1; pass <= n; pass++)
{
for (i = 1; i <= n + 1; i++)
for (j = 1; j <= n + 1; j++)
{
if ((dist[i] + w[i, j]) < dist[j])
{
parent[j] = i;
dist[j] = dist[i] + w[i, j];
}
}
}
for (i = 1; i <= n + 1; i++)
for (j = 1; j <= n + 1; j++)
{
if ((dist[i] + w[i, j]) < dist[j])
return 0;
}
return 1;
}
public int InotinN(int[] N,int i,int n)
{
for (var j = 1; j <= n; j++)
if (N[j] == i)
return 0;
return 1;
}
public int Min(int a, int b)
{
return a < b ? a : b;
}
public int Print(int x,int[] D,int[,] w,int source,int[] N)
{
if (D[x] == w[source, x])
Console.Write(" {0:D} --> {1:D} ", source, x);
else
{
while (true)
{
if (D[x] == (D[N[j]] + w[N[j], x]))
{
Print(N[j],D,w,source,N);
break;
}
j++;
}
Console.Write(" --> {0:D} ", x);
}
return 0;
}
public int Dijikstras(int[] D, int[] N, int source, int n, int[,] w,int k)
{
int i,j,x=0,min;
for (i = 1; i <= n; i++)
if (i != source)
D[i] = w[source, i];
while (true)
{
min = 999;
for (i = 1; i <= n; i++)
{
if (InotinN(N,i,n) != 0 && D[i] < min)
{
min = D[i];
x = i;
}
}
if (InotinN(N,x,n) != 0)
N[k++] = x;
else
N[k++] = 0;
if (k == n + 1)
break;
else
{
for (i = 1; i <= n; i++)
if (InotinN(N,i,n) != 0)
D[i] = Min(D[i], D[x] + w[x, i]);
}
}
return 0;
}
}
}
Output:
(V1,V2):1
1 --> 2
(V1,V3):3
1 --> 3
(V2,V1):2
2 --> 1
(V2,V3):4
2 --> 3
3 --> 2
(V3,V1):4
3 --> 2 --> 1