# python code for the above approach:
class Solution:
def shortest_paths(self, grid, V):
dist = [float('inf')] * V
# Taking 0 as our source
dist[0] = 0
# Relaxing V-1 times
for i in range(V):
# For each value in the given
# list of [u, v, wt]
for u, v, wt in grid:
# If there exists a better
# distance and previous dist
# of u should not be infinite
if dist[u] != float('inf') and dist[u] + wt < dist[v]:
dist[v] = dist[u] + wt
# If negative cycle exists then
# it will still reduce for
# Vth traversal
for u, v, wt in grid:
if dist[u] != float('inf') and dist[u] + wt < dist[v]:
print("ERROR ALERT, Negative Cycle exists")
print("The shortest distances from ")
for i in range(V):
print(" 0 to", i, "--->", dist[i])
# Driver code
if __name__ == "__main__":
V = 6
grid = [[0, 1, 2], [0, 3, 5], [0, 4, 3], [1, 0, 3], [1, 5, 6], [
1, 2, 2], [1, 3, 2], [2, 5, 1], [2, 3, 1], [3, 4, 1], [4, 3, 2]]
s1 = Solution()
# Function call
s1.shortest_paths(grid, V)