Simple C++ code, but slow


  • 0
    S
    class Solution {
    public:
        bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
            if(numCourses==0) return true;
            map<int,int> m;
            for(auto p :prerequisites){
                if(p.first>=numCourses||p.second>=numCourses) return false;
                m[p.first]=p.second;
            }
            //0>2, 1>2 , 3>0, 2>0 // 1>2, 2>3 , 3>1
            int s = m.size();
            for(auto p:prerequisites){
                int x =p.second;
                int count=0;
                while(m.count(x)!=0){
                    count++;
                    if(count>s) return false;
                    x=m[x];
                    if(x==p.first) return false;
                }
            }
            return true;
            
        }
    };```

Log in to reply
 

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