|
| 1 | +// Runtime: 137 ms (Top 83.42%) | Memory: 90.50 MB (Top 95.59%) |
| 2 | + |
1 | 3 | class Solution {
|
2 |
| -public: |
3 |
| - |
4 |
| - int maxLength = -1; |
5 |
| - |
6 |
| - void getcycle(vector<int> &edges,int si,vector<bool>& visit,vector<int>& store){ |
7 |
| - if(si == -1)return ; |
8 |
| - if(visit[si]){ |
9 |
| - int count = -1; |
10 |
| - for(int i =0;i<store.size();i++){ |
11 |
| - if(store[i]==si){ |
12 |
| - count = i; |
13 |
| - break; |
14 |
| - } } |
15 |
| - |
16 |
| - if(count==-1)return; |
17 |
| - int size = (store.size()-count); |
18 |
| - maxLength = max(maxLength,size); |
19 |
| - return ; |
20 |
| - } |
21 |
| - |
22 |
| - visit[si] = true; |
23 |
| - store.push_back(si); |
24 |
| - getcycle(edges,edges[si],visit,store); |
25 |
| - |
26 |
| - |
27 |
| - return ; |
28 |
| - |
29 |
| - } |
30 |
| - |
31 |
| - |
32 |
| - |
33 |
| - int longestCycle(vector<int>& edges) { |
34 |
| - |
35 |
| - vector<bool> visit(edges.size(),0); |
36 |
| - |
37 |
| - for(int i =0;i<edges.size();i++){ |
38 |
| - |
39 |
| - if(visit[i])continue; |
40 |
| - vector<int> store; |
41 |
| - getcycle(edges,i,visit,store); |
42 |
| - |
43 |
| - } |
44 |
| - |
45 |
| - return maxLength; |
46 |
| - |
| 4 | + public: |
| 5 | + int longestCycle(vector<int>& edges) { |
| 6 | + int ans = -1; // Initialize the answer to -1 |
| 7 | + int time = 1; // Initialize the current time step to 1 |
| 8 | + vector<int> timeVisited(edges.size()); // Initialize a vector to store the time at which each node was first visited |
| 9 | + |
| 10 | + // Iterate through each node in the graph |
| 11 | + for (int i = 0; i < edges.size(); ++i) { |
| 12 | + if (timeVisited[i]) // If the node has already been visited, skip it |
| 13 | + continue; |
| 14 | + const int startTime = time; // Record the start time of the current traversal |
| 15 | + int u = i; // Initialize the current node to the ith node |
| 16 | + // Traverse the graph until the end of the path is reached or a visited node is encountered |
| 17 | + while (u != -1 && !timeVisited[u]) { |
| 18 | + timeVisited[u] = time++; // Record the current time step and increment time |
| 19 | + u = edges[u]; // Move to the next node in the path |
| 20 | + } |
| 21 | + // If a cycle is found that includes the current node, update the answer |
| 22 | + if (u != -1 && timeVisited[u] >= startTime) |
| 23 | + ans = max(ans, time - timeVisited[u]); |
47 | 24 | }
|
| 25 | + |
| 26 | + return ans; // Return the length of the longest cycle found |
| 27 | + } |
48 | 28 | };
|
| 29 | + |
0 commit comments