jeudi 20 mai 2021

Finding a cycle path in directed graph

I am making a directed Graph class. I want find if there is any Cycle and update a vector with it's path accordingly. My Function some times work but others add two times the last edge of the path.So i guess it needs to be tydied up.

Example: having a Graph with these paths

0->1, 0->2, 1->2, 2->3, 3->4, 4->0, 4->6, 1->5, 5->6

should set the vector to [0 2 3 4] or anything else valid.

What I have tried:

#include <iostream>  
#include <vector>  
#include <list>  
#include <algorithm>  
using namespace std;  
  
class Graph {  
private:  
    int V;  
    list<int> *adj;  
    bool isCyclicHelp(int v, bool visited[], bool *rs, vector<int> &path) const{  
        if(visited[v] == false) {  
            visited[v] = true;  
            rs[v] = true;  
  
            list<int>::iterator i;  
            for(i=adj[v].begin(); i!=adj[v].end(); i++) {  
                if(!visited[*i] && isCyclicHelp(*i, visited, rs, path)) {  
                    path.push_back(*i);  
                    return true;  
                }  
                else if(rs[*i]) {  
                    return true;  
                }  
            }  
        }  
        rs[v] = false;  
        path.pop_back();  
        return false;  
    }  
public:  
    Graph(int V) {  
        this->V = V;  
        adj = new list<int>[V];  
    }  
    ~Graph() {  
  
    }  
    void addEdge(int v, int w) {  
        if(v != w) {  
            adj[v].push_back(w);  
        }  
    }  
    bool cycle(vector<int> &path) const {  
        bool *visited = new bool[V];  
        bool *recStack = new bool[V];  
        for(int i=0; i<V; i++) {  
            visited[i] = false;  
            recStack[i] = false;  
        }  
  
        for(int i=0; i<V; i++) {  
            path.push_back(i);  
            if(Graph::isCyclicHelp(i, visited, recStack, path)) {  
                reverse(path.begin(), path.end());  
                return true;  
            }  
            path.clear();  
        }  
        path.clear();  
        return false;  
    }  
};

Aucun commentaire:

Enregistrer un commentaire