File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change @@ -72,3 +72,40 @@ const canFinish = function(vertices, edges) {
72
72
}
73
73
return sortedOrder . length === vertices ? true : false
74
74
}
75
+
76
+ // another
77
+
78
+ /**
79
+ * @param {number } numCourses
80
+ * @param {number[][] } prerequisites
81
+ * @return {boolean }
82
+ */
83
+ const canFinish = function ( numCourses , prerequisites ) {
84
+ const set = new Set ( ) , hash = { }
85
+ for ( let i = 0 ; i < prerequisites . length ; i ++ ) {
86
+ const [ cur , pre ] = prerequisites [ i ]
87
+ if ( hash [ cur ] == null ) hash [ cur ] = new Set ( )
88
+ hash [ cur ] . add ( pre )
89
+ }
90
+ const q = [ ]
91
+
92
+ for ( let i = 0 ; i < numCourses ; i ++ ) {
93
+ if ( hash [ i ] == null ) q . push ( i )
94
+ }
95
+ let visited = 0
96
+
97
+ while ( q . length ) {
98
+ const cur = q . shift ( )
99
+ visited ++
100
+ Object . keys ( hash ) . forEach ( k => {
101
+ if ( hash [ k ] . has ( cur ) ) {
102
+ hash [ k ] . delete ( cur )
103
+ }
104
+ if ( hash [ k ] . size === 0 ) {
105
+ delete hash [ k ]
106
+ q . push ( + k )
107
+ }
108
+ } )
109
+ }
110
+ return visited === numCourses
111
+ } ;
You can’t perform that action at this time.
0 commit comments