Skip to content

Commit

Permalink
Added solution for Longest Cycle in a Graph
Browse files Browse the repository at this point in the history
  • Loading branch information
Sagar-Mondal authored Oct 27, 2022
1 parent 1450383 commit b6c051b
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions Longest_Cycle_in_a_Graph.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
int longestCycle(vector<int>& edges) {
int n = edges.size(), ans = -1;
vector<int> idx(n);
for (int i = 0, k = 1; i < n; i++) {
int j = i, curk = k;
while (j != -1 && !idx[j]) {
idx[j] = k++;
j = edges[j];
}
if (j != -1 && idx[j] >= curk)
ans = max(ans, k - idx[j]);
}
return ans;
}

0 comments on commit b6c051b

Please sign in to comment.