Finding all cycles in a directed graph

前端 未结 17 2173
渐次进展
渐次进展 2020-11-22 05:47

How can I find (iterate over) ALL the cycles in a directed graph from/to a given node?

For example, I want something like this:

A->B->A
A->B         


        
17条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 06:04

    DFS c++ version for the pseudo-code in second floor's answer:

    void findCircleUnit(int start, int v, bool* visited, vector& path) {
        if(visited[v]) {
            if(v == start) {
                for(auto c : path)
                    cout << c << " ";
                cout << endl;
                return;
            }
            else 
                return;
        }
        visited[v] = true;
        path.push_back(v);
        for(auto i : G[v])
            findCircleUnit(start, i, visited, path);
        visited[v] = false;
        path.pop_back();
    }
    

提交回复
热议问题