-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheckIfPrerequisite.cpp
More file actions
28 lines (28 loc) · 928 Bytes
/
checkIfPrerequisite.cpp
File metadata and controls
28 lines (28 loc) · 928 Bytes
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
class Solution {
public:
vector<bool> checkIfPrerequisite(int numCourses, vector<vector<int>>& prerequisites, vector<vector<int>>& queries) {
child.resize(numCourses, unordered_set<int>());
isReachable.resize(numCourses, vector<int>(numCourses, 0));
for (auto v: prerequisites) child[v[0]].insert(v[1]);
vector<bool> ans;
for (auto v: queries) {
ans.push_back(dfs(v[0], v[1]));
}
return ans;
}
bool dfs(int a, int b) {
if (isReachable[a][b] != 0) return (isReachable[a][b] == 1);
if (child[a].count(b)) return isReachable[a][b] = 1;
int res = -1;
for (int ch: child[a]) {
if (dfs(ch, b)) {
res = 1;
break;
}
}
return (isReachable[a][b] = res) == 1;
}
private:
vector<vector<int> > isReachable;
vector<unordered_set<int> > child;
};