File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
BFS/1462.Course-Schedule-IV Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ vector<bool > checkIfPrerequisite (int n, vector<vector<int >>& prerequisites, vector<vector<int >>& queries)
4+ {
5+ vector<unordered_set<int >>next (n);
6+ vector<int >inDegree (n,0 );
7+ vector<unordered_set<int >>preSet (n);
8+
9+ for (auto edge: prerequisites)
10+ {
11+ next[edge[0 ]].insert (edge[1 ]);
12+ inDegree[edge[1 ]] += 1 ;
13+ }
14+
15+ queue<int >q;
16+ for (int i=0 ; i<n; i++)
17+ {
18+ preSet[i].insert (i);
19+ if (inDegree[i]==0 )
20+ q.push (i);
21+ }
22+
23+ while (!q.empty ())
24+ {
25+ int cur = q.front ();
26+ q.pop ();
27+
28+ for (int next: next[cur])
29+ {
30+ for (auto x: preSet[cur])
31+ preSet[next].insert (x);
32+
33+ inDegree[next] -= 1 ;
34+ if (inDegree[next]==0 )
35+ q.push (next);
36+ }
37+ }
38+
39+ vector<bool >rets;
40+ for (auto query: queries)
41+ {
42+ rets.push_back (preSet[query[1 ]].find (query[0 ])!=preSet[query[1 ]].end ());
43+ }
44+ return rets;
45+ }
46+ };
You can’t perform that action at this time.
0 commit comments