File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number[] } edges
3
+ * @return {number }
4
+ */
5
+ const longestCycle = function ( edges ) {
6
+ const n = edges . length ;
7
+ const visited = new Array ( n ) . fill ( false ) ;
8
+ const ind = new Array ( n ) . fill ( 0 ) ;
9
+ for ( let i = 0 ; i < n ; i ++ ) {
10
+ if ( edges [ i ] !== - 1 ) {
11
+ ind [ edges [ i ] ] ++ ;
12
+ }
13
+ }
14
+ let q = [ ]
15
+ for ( let i = 0 ; i < n ; i ++ ) {
16
+ if ( ind [ i ] === 0 ) {
17
+ q . push ( i ) ;
18
+ }
19
+ }
20
+ while ( q . length ) {
21
+ const node = q . pop ( )
22
+ visited [ node ] = true ;
23
+ const nxt = edges [ node ] ;
24
+ if ( nxt !== - 1 ) {
25
+ ind [ nxt ] -- ;
26
+ if ( ind [ nxt ] === 0 ) {
27
+ q . push ( nxt ) ;
28
+ }
29
+ }
30
+ }
31
+ let res = - 1
32
+ for ( let i = 0 ; i < n ; i ++ ) {
33
+ if ( ! visited [ i ] ) {
34
+ let cnt = 0
35
+ let cur = i
36
+ while ( ! visited [ cur ] ) {
37
+ visited [ cur ] = true
38
+ cur = edges [ cur ]
39
+ cnt ++
40
+ }
41
+ res = Math . max ( res , cnt )
42
+ }
43
+ }
44
+
45
+ return res
46
+ } ;
47
+
48
+ // another
49
+
1
50
/**
2
51
* @param {number[] } edges
3
52
* @return {number }
You can’t perform that action at this time.
0 commit comments