Detect a negative cycle in a Graph using the Shortest Path Faster Algorithm



The Shortest Path Faster Algorithm is an improved or more optimized version of the Bellman-Ford Algorithm. It calculates the single source's shortest path in a weighted directed graph. This algorithm is especially suitable for graphs with negatively weighted edges.

Algorithm

Given a weighted directed graph and a source vertex , the algorithm finds the shortest path from , to each vertex , in the graph. The length of thh shortest path from to is stored in for each vertex .

procedure Shortest-Path-Faster-Algorithm(G, s) for each vertex v ? s in V(G) d(v) := ? d(s) := 0 push s into Q while Q is not empty do u := poll Q for each edge (u, v) in E(G) do if d(u) + w(u, v) < d(v) then d(v) := d(u) + w(u, v) if v is not in Q then push v into Q

Problem Statement

Given a graph G containing N nodes having values from 0 to N-1, a source S and an array A[][3] of the type {u, v, w} denoting a directed edge from u to v having weight w. The aim is to find if there exists a negative cycle in the graph from the given source.

Sample Example 1

Input: N = 3, S = 0, A[][] = {{0, 1, -2}, {1, 2, 1}, {2, 0, -1}} Output: True

Explanation

Starting from 0, the graph contains the following cycle

0 -> 1 -> 2 -> 0

Sum of weights of the above cycle = (-2) + 1 + (-1) = (-2)

Thus, graph contains cycle of negative weight.

Sample Example 2

Input: N = 3, S = 0, A[][] = {{0, 1, -2}, {1, 2, 1}, {0, 2, -1}} Output: False

Explanation

Starting from 0, the graph does not contain a cycle.

Solution Approach

Using SPFA to detect a negative weighted cycle in a graph, we follow the following steps

  • Create arrays distance[] with infinity value, visited[] with false and count[] with 0 which will contain the number of times a node has been relaxed.

  • Then traverse the graph using the SPFA algorithm.

  • Increment the count for each vertex upon relaxation i.e. updating the cost of each vertex connected to v if the cost improves by including v in the path.

  • Return true if some vertex is relaxed for the Nth time else returns false.

Example: C++ Implementation

The following code uses the SPFA algorithm to find the negative cycle in the graph.

Open Compiler
#include <bits/stdc++.h> using namespace std; bool SFPA(int V, int S, int E[][3], int M){ // Adjacency list of the given graph vector<pair<int, int>> g[V]; // Create Adjacency List for (int i = 0; i < M; i++){ int u = E[i][0]; int v = E[i][1]; int w = E[i][2]; g[u].push_back({v, w}); } vector<int> distance(V, INT_MAX); vector<bool> visted(V, false); vector<int> count(V, 0); // Distance from src to src is 0 distance[S] = 0; queue<int> q; q.push(S); // Mark source as visited visted[S] = true; while (!q.empty()) { int u = q.front(); q.pop(); visted[u] = false; // Relaxing all edges of vertex from the Queue for (pair<int, int> x : g[u]) { int v = x.first; int cost = x.second; // Update the distance[v] to minimum distance if (distance[v] > distance[u] + cost) { distance[v] = distance[u] + cost; // If vertex v is in Queue if (!visted[v]) { q.push(v); visted[v] = true; count[v]++; // Negative cycle if (count[v] >= V) return true; } } } } // No cycle found return false; } int main(){ int N = 4; int S = 0; int M = 4; // Given Edges with weight int E[][3] = {{0, 1, 1}, {1, 2, -1}, {2, 3, -1}, {3, 0, -1}}; // If cycle is present if (SFPA(N, S, E, M) == true) cout << "True" << endl; else cout << "False" << endl; return 0; }

Output

True

Conclusion

In conclusion, in order to detect negative cycle in a graph, Shortest Path Fast Algorithm can be used as it is most efficient when dealing with negative weights of edges. The above solution gives a time complexity of O(N*M) and a space complexity of O(N).

Updated on: 2023-10-25T13:07:40+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements