Cycle detection using dfs

segmentation fault


using namespace std;

template<typename T>
class graph{

    map<T,list<T> >m;

    public:

    void add_edge(T u, T v, bool bidir=true){
        m[u].push_back(v);

        if(bidir){
            m[v].push_back(u);
        }
    }

    bool cyclic_util(T node,map<T,bool> &visited, map<T,bool> &re_stack){

        visited[node] = true;
        re_stack[node] = true;

        for(auto i: m[node]){

            if(visited[i] && cyclic_util(i,visited,re_stack)){
                return true;
            }
            else if(visited[i] && re_stack[i]){
                return true;
            }
        }

        re_stack[node] = false;
        return false;
    }

    bool isCyclic(){

        map<T,bool> visited;
        map<T,bool> re_stack;

        for(auto i: m){
            visited[i.first] = false;
        }

        for(auto i: m){
            if(!visited[i.first]){
               bool cycle = cyclic_util(i.first,visited,re_stack);
               if(cycle == true) return true;
            }
        }

        return false;
    }
};

int main(){

    graph<int> g;

    g.add_edge(0,2,false);
    g.add_edge(0,1,false);
    g.add_edge(2,3,false);
    g.add_edge(2,4,false);
    g.add_edge(3,0,false);
    g.add_edge(4,5,false);
    g.add_edge(1,5,false);

   bool cycle = g.isCyclic();

    if(cycle == true) cout<<"cycle detected"<<endl;
    else cout<<"cycle not detected"<<endl;
}```

https://ide.geeksforgeeks.org/lUSTipm5Qp – link to code