jayati

Longest Cycle in a Graph

Mar 26th, 2023
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.53 KB | None | 0 0
  1. class Solution {
  2.  public:
  3.   int longestCycle(vector<int>& edges) {
  4.     int ans = -1;
  5.     int time = 1;
  6.     vector<int> timeVisited(edges.size());
  7.     for (int i = 0; i < edges.size(); ++i) {
  8.       if (timeVisited[i])
  9.         continue;
  10.       const int startTime = time;
  11.       int u = i;
  12.       while (u != -1 && !timeVisited[u]) {
  13.         timeVisited[u] = time++;
  14.         u = edges[u];
  15.       }
  16.       if (u != -1 && timeVisited[u] >= startTime)
  17.         ans = max(ans, time - timeVisited[u]);
  18.     }
  19.    return ans;
  20.   }
  21. };
  22.  
Advertisement
Add Comment
Please, Sign In to add comment