forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCourse Schedule IV.cpp
55 lines (43 loc) · 1.22 KB
/
Course Schedule IV.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Runtime: 270 ms (Top 87.54%) | Memory: 69.3 MB (Top 32.97%)
// question similar to find all ancestors of current node
class Solution {
public:
void dfs(vector<vector<int>>&adj,vector<set<int>>&Anc,int u,int par,vector<int>&vis)
{
if( vis[u] != 0 )
return ;
vis[u] = 1 ;
for(auto&v:adj[u])
{
if( vis[v] == 0 )
{
Anc[v].insert(par) ;
dfs(adj,Anc,v,par,vis) ;
}
}
return ;
}
vector<bool> checkIfPrerequisite(int numCourses, vector<vector<int>>& prerequisites, vector<vector<int>>& queries) {
int n = numCourses ;
vector<vector<int>>adj(n);
vector<set<int>>Anc(n);
vector<bool>ans;
for(auto&edge:prerequisites)
{
adj[edge[0]].push_back(edge[1]) ;
}
for(int i=0;i<n;i++)
{
vector<int>vis(n,0);
dfs(adj,Anc,i,i,vis) ;
}
for(auto&EachQuery:queries)
{
if( Anc[EachQuery[1]].find(EachQuery[0]) != Anc[EachQuery[1]].end() )
ans.push_back(true);
else
ans.push_back(false) ;
}
return ans ;
}
};