File tree 1 file changed +53
-0
lines changed
1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number } numCourses
3
+ * @param {number[][] } prerequisites
4
+ * @param {number[][] } queries
5
+ * @return {boolean[] }
6
+ */
7
+ var checkIfPrerequisite = function ( numCourses , prerequisites , queries ) {
8
+ const g = { }
9
+ const n = numCourses
10
+ const indegree = Array ( n ) . fill ( 0 )
11
+ for ( const [ a , b ] of prerequisites ) {
12
+ if ( ! g [ a ] ) {
13
+ g [ a ] = [ ]
14
+ }
15
+ g [ a ] . push ( b )
16
+ indegree [ b ] ++
17
+ }
18
+ const q = [ ]
19
+ for ( let i = 0 ; i < n ; i ++ ) {
20
+ if ( indegree [ i ] === 0 ) {
21
+ q . push ( i )
22
+ }
23
+ }
24
+ const res = [ ]
25
+ const hash = { }
26
+ for ( const e of q ) {
27
+ dfs ( e , new Set ( ) )
28
+ }
29
+ for ( let i = 0 ; i < queries . length ; i ++ ) {
30
+ const [ a , b ] = queries [ i ]
31
+ res . push ( hash [ a ] && hash [ a ] . has ( b ) )
32
+ }
33
+
34
+ return res
35
+ function dfs ( cur , set ) {
36
+ if ( hash [ cur ] ) {
37
+ return hash [ cur ]
38
+ }
39
+ hash [ cur ] = new Set ( )
40
+ if ( g [ cur ] ) {
41
+ for ( const e of g [ cur ] ) {
42
+ for ( const x of dfs ( e , set ) ) {
43
+ hash [ cur ] . add ( x )
44
+ }
45
+ }
46
+ }
47
+ hash [ cur ] . add ( cur )
48
+ return hash [ cur ]
49
+ }
50
+ } ;
51
+
52
+ // another
53
+
1
54
/**
2
55
* @param {number } numCourses
3
56
* @param {number[][] } prerequisites
You can’t perform that action at this time.
0 commit comments