MCPcopy Create free account
hub / github.com/codedecks-in/LeetCode-Solutions / Solution

Class Solution

C++/Course-Schedule.cpp:13–55  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

11// if a back edge exists in the graph, it implies that there is a cycle, thus it is not possible to finish all the courses
12
13class Solution {
14public:
15
16 // helper function
17 bool dfs(vector<vector<int>>& adjlist, vector<int>& visited, int i) {
18
19 // base condition
20 if(visited[i]==1) return false;
21 visited[i]=1; // mark as being visited
22
23 for(int a:adjlist[i]) {
24 if(!dfs(adjlist, visited, a)) // dfs(adjlist, visited, a) == false
25 return false;
26 }
27
28 visited[i] = 2; // mark as visited
29 return true;
30 }
31
32
33 bool canFinish(int numc, vector<vector<int>>& prereq) {
34
35 // numc: numCourses
36 // prereq: prerequisites
37
38 // create adjacency list
39 vector<vector<int>> adjlist(numc, vector<int>());
40 for(vector<int>& p:prereq)
41 adjlist[p[0]].push_back(p[1]);
42
43 vector<int> visited(numc, 0);
44 // unvisited: 0
45 // being visited: 1
46 // completely visited: 2
47 for(int i=0; i<numc; i++) {
48 if(visited[i]==0 && !dfs(adjlist, visited, i))
49 return false;
50 }
51
52 return true;
53 }
54
55};

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected