C++ · Solution

Find All Cycles

This C++ solution uses graph traversal for Find All Cycles. Read the reasoning, inspect the code, or try your own test case below.

Graphs & treesGraph traversalC++46 lines
Solution090of 248
Download C++ file ↓ Search the library → Open full Code Lab ↗ Report an issue ↗

Approach

Graph traversal

Find All Cycles: traverse the graph recursively or with an explicit stack, carrying the information needed for each component, path, or subtree.

Depth-first searchGraphs

Problem and code

Useful links.

Written by benbenyaojifen. Try the problem first, then compare your approach with the code.

View exact source file ↗
Implementation

find_all_cycles.cpp

C++

    #include <bits/stdc++.h>
    using namespace std;
    #define int long long
    vector<int> to;
    vector<int> color, parent;
    vector<vector<int>> cycles;
    void dfs(int u){
        color[u] = 1; //visiting
        int v = to[u];
        if(color[v] == 0){ // unvisited 
            parent[v] = u;
            dfs(v);
        }else if(color[v] == 1){
            vector<int> cyc;
            int x = v;
            do {
                cyc.push_back(x);
                x = to[x];
            } while(x != v);
            int pos = min_element(cyc.begin(), cyc.end()) - cyc.begin();
            rotate(cyc.begin(), cyc.begin() + pos, cyc.end());
            cycles.push_back(move(cyc));
        }
        color[u] = 2; // done
    }
    signed main(){
        ios::sync_with_stdio(0); cin.tie(0);
        int n; cin >> n;
        to.assign(n + 1, 0);
        for(int i = 1; i <= n; i++){
            cin >> to[i];
        }
        color.assign(n + 1, 0);
        parent.assign(n + 1, -1);
        for(int i = 1; i <= n; i++){
            if(color[i] == 0) dfs(i);
        }
        sort(cycles.begin(), cycles.end());
        cout << cycles.size() << '\n';
        for(auto &c : cycles){
            for(int i = 0; i < c.size(); i++){
                cout << c[i] << (i == c.size() - 1 ? "\n" : " ");
            }
        }
        return 0;
    }
        

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗Keep studying →

Test this problem

Run your code here.

Paste your code, run a test case, compare the output, or trace selected values.

Full trace, comparison & stress testing ↗
StatusReady
Output
No run yet.
Diagnostics
No diagnostics yet.

Each run is isolated and has strict limits. Passing one test does not guarantee the judge will accept the solution.