using System;
using System.Collections.Generic;
class Solution
{
public void ShortestPaths(List<List<int>> grid, int V)
{
List<int> dist = new List<int>(new int[V]);
for (int i = 0; i < V; i++)
{
dist[i] = int.MaxValue;
}
dist[0] = 0;
for (int i = 0; i < V - 1; i++)
{
foreach (var it in grid)
{
int u = it[0];
int v = it[1];
int wt = it[2];
if (dist[u] != int.MaxValue
&& dist[u] + wt < dist[v])
{
dist[v] = dist[u] + wt;
}
}
}
for (int i = 0; i < V; i++)
{
foreach (var it in grid)
{
int u = it[0];
int v = it[1];
int wt = it[2];
if (dist[u] != int.MaxValue && dist[u] + wt < dist[v])
{
Console.WriteLine("ERROR ALERT, Negative Cycle exists");
return;
}
}
}
Console.WriteLine("The shortest distances from ");
for (int i = 0; i < V; i++)
{
Console.WriteLine($"0 to {i} ---> {(dist[i] == int.MaxValue ? "INF" : dist[i].ToString())}");
}
}
}
class Program
{
static void Main()
{
int V = 6;
List<List<int>> grid = new List<List<int>>
{
new List<int> { 0, 1, 2 },
new List<int> { 0, 3, 5 },
new List<int> { 0, 4, 3 },
new List<int> { 1, 0, 3 },
new List<int> { 1, 5, 6 },
new List<int> { 1, 2, 2 },
new List<int> { 1, 3, 2 },
new List<int> { 2, 5, 1 },
new List<int> { 2, 3, 1 },
new List<int> { 3, 4, 1 },
new List<int> { 4, 3, 2 }
};
Solution s1 = new Solution();
s1.ShortestPaths(grid, V);
}
}