File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Expand file tree Collapse file tree 1 file changed +58
-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
+ const checkIfPrerequisite = function ( numCourses , prerequisites , queries ) {
8
+ const n = numCourses , m = prerequisites . length
9
+ const graph = { } , inDegree = Array ( n ) . fill ( 0 )
10
+
11
+ for ( const [ s , e ] of prerequisites ) {
12
+ if ( graph [ s ] == null ) graph [ s ] = [ ]
13
+ inDegree [ e ] ++
14
+ graph [ s ] . push ( e )
15
+ }
16
+
17
+ let q = [ ]
18
+
19
+ for ( let i = 0 ; i < n ; i ++ ) {
20
+ if ( inDegree [ i ] === 0 ) q . push ( i )
21
+ }
22
+
23
+ const hash = { }
24
+
25
+ while ( q . length ) {
26
+ const size = q . length
27
+ const nxt = [ ]
28
+ for ( let i = 0 ; i < size ; i ++ ) {
29
+ const cur = q [ i ]
30
+ for ( const e of ( graph [ cur ] || [ ] ) ) {
31
+ inDegree [ e ] --
32
+ if ( hash [ e ] == null ) hash [ e ] = new Set ( )
33
+ hash [ e ] . add ( cur )
34
+ for ( const dep of ( hash [ cur ] || [ ] ) ) {
35
+ hash [ e ] . add ( dep )
36
+ }
37
+
38
+ if ( inDegree [ e ] === 0 ) {
39
+ nxt . push ( e )
40
+ }
41
+ }
42
+ }
43
+
44
+ q = nxt
45
+ }
46
+
47
+ const res = [ ]
48
+ for ( const [ p , e ] of queries ) {
49
+ if ( hash [ e ] && hash [ e ] . has ( p ) ) res . push ( true )
50
+ else res . push ( false )
51
+ }
52
+
53
+ return res
54
+ }
55
+
56
+ // another
57
+
58
+
1
59
/**
2
60
* @param {number } numCourses
3
61
* @param {number[][] } prerequisites
You can’t perform that action at this time.
0 commit comments