C++ DFS solution


  • 0
    J
    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
        vector<vector<int>> adjList (numCourses, vector<int>());
        
        for(int i = 0; i<prerequisites.size(); i++) {
            int course = prerequisites[i].first;
            int preCourse = prerequisites[i].second;
            adjList[course].push_back(preCourse);
        }
        
        vector<bool> rec (adjList.size(), false);
        for(int i = 0; i<adjList.size(); i++) 
            if(checkDAG(adjList, rec, i) == false)
                return false;
    
        return true;
    }
    
    bool checkDAG(vector<vector<int>>& adjList, vector<bool>& rec, int node) {
        rec[node] = true;
        for(int i = 0; i<adjList[node].size(); i++) {
            if(rec[adjList[node][i]]) return false;
            if(checkDAG(adjList, rec, adjList[node][i]) == false)
                return false;
        }
        rec[node] = false;
        return true;
    }

Log in to reply
 

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