Why is This code giving tle??


  • -4

    class Solution {
    public:
    bool dfs(vector< set<int> > pre,int v,vector<bool> vis,vector<bool> stc){
    if(!vis[v]){
    vis[v] = true;
    stc[v] = true;
    set<int>::iterator i;
    for(i = pre[v].begin();i!=pre[v].end();i++ ){
    if(!vis[*i]&&dfs(pre,*i,vis,stc))
    return true;
    else if(stc[*i])
    return true;
    }
    }
    stc[v] = false;
    return false;
    }
    bool canFinish(int numCourses, vector<pair<int, int>>& pre) {
    if(pre.size()==0)
    return true;
    vector< set<int> > v(numCourses);
    vector<bool> vis(numCourses,false),stc(numCourses,false);
    for(int i=0;i<pre.size();i++)
    v.at(pre[i].second).insert(pre[i].first);
    for(int i=0;i<numCourses;i++){
    if(!vis[i])
    if(dfs(v,i,vis,stc))
    return false;
    }
    return true;
    }
    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.