|
| 1 | +PROBLEM: |
| 2 | + |
| 3 | + |
| 4 | + |
| 5 | + |
| 6 | +There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1. |
| 7 | +Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] |
| 8 | +Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses? |
| 9 | + |
| 10 | + |
| 11 | +Example 1: |
| 12 | +Input: numCourses = 2, prerequisites = [[1,0]] |
| 13 | +Output: true |
| 14 | +Explanation: There are a total of 2 courses to take. |
| 15 | + To take course 1 you should have finished course 0. So it is possible. |
| 16 | + |
| 17 | +Example 2: |
| 18 | +Input: numCourses = 2, prerequisites = [[1,0],[0,1]] |
| 19 | +Output: false |
| 20 | +Explanation: There are a total of 2 courses to take. |
| 21 | + To take course 1 you should have finished course 0, and to take course 0 you should |
| 22 | + also have finished course 1. So it is impossible. |
| 23 | + |
| 24 | + |
| 25 | +Constraints: |
| 26 | + |
| 27 | +The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented. |
| 28 | +You may assume that there are no duplicate edges in the input prerequisites. |
| 29 | +1. 1 <= numCourses <= 10^5 |
| 30 | + |
| 31 | + |
| 32 | + |
| 33 | + |
| 34 | + |
| 35 | +SOLUTION: |
| 36 | + |
| 37 | + |
| 38 | +//Detect cycle in directed graph(using dfs/kahn's algo) |
| 39 | + |
| 40 | + |
| 41 | + |
| 42 | +class Solution { |
| 43 | +public: |
| 44 | + |
| 45 | + bool dfs(vector<int> adj[],vector<bool>& vis,vector<bool>& ancestor,int s) |
| 46 | + { |
| 47 | + vis[s]=true; |
| 48 | + ancestor[s]=true; |
| 49 | + |
| 50 | + for(auto k:adj[s]) |
| 51 | + { |
| 52 | + if(!vis[k]) |
| 53 | + { |
| 54 | + if(dfs(adj,vis,ancestor,k)) |
| 55 | + return true; |
| 56 | + } |
| 57 | + |
| 58 | + else if(vis[k]==true && ancestor[k]==true) |
| 59 | + return true; |
| 60 | + } |
| 61 | + |
| 62 | + ancestor[s]=false; |
| 63 | + return false; |
| 64 | + } |
| 65 | + |
| 66 | + bool canFinish(int numCourses, vector<vector<int>>& prerequisites) { |
| 67 | + |
| 68 | + int i,n,a,b; |
| 69 | + vector<int> adj[numCourses]; |
| 70 | + vector<bool> vis(numCourses,false); |
| 71 | + vector<bool> ancestor(numCourses,false); |
| 72 | + |
| 73 | + n=prerequisites.size(); |
| 74 | + |
| 75 | + for(i=0;i<n;i++) |
| 76 | + { |
| 77 | + a=prerequisites[i][0]; |
| 78 | + b=prerequisites[i][1]; |
| 79 | + |
| 80 | + adj[b].push_back(a); |
| 81 | + } |
| 82 | + |
| 83 | + for(i=0;i<numCourses;i++) |
| 84 | + { |
| 85 | + if(!vis[i]) |
| 86 | + { |
| 87 | + if(dfs(adj,vis,ancestor,i)) |
| 88 | + return false; |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + return true; |
| 93 | + |
| 94 | + |
| 95 | + } |
| 96 | +}; |
0 commit comments