File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number } n
3
+ * @param {number[][] } edges
4
+ * @return {number }
5
+ */
6
+ const findShortestCycle = function ( n , edges ) {
7
+ let res = Infinity
8
+ const graph = new Map ( )
9
+ for ( const [ u , v ] of edges ) {
10
+ if ( graph . get ( u ) == null ) graph . set ( u , [ ] )
11
+ if ( graph . get ( v ) == null ) graph . set ( v , [ ] )
12
+ graph . get ( u ) . push ( v )
13
+ graph . get ( v ) . push ( u )
14
+ }
15
+ for ( let i = 0 ; i < n ; i ++ ) {
16
+ bfs ( i )
17
+ }
18
+
19
+ if ( res === Infinity ) return - 1
20
+ return res
21
+
22
+ function bfs ( src ) {
23
+ const parent = Array ( n ) , dis = Array ( n ) . fill ( Infinity )
24
+ let q = [ ]
25
+ dis [ src ] = 0
26
+ q . push ( src )
27
+ while ( q . length ) {
28
+ const node = q . shift ( )
29
+ for ( const nxt of ( graph . get ( node ) || [ ] ) ) {
30
+ if ( dis [ nxt ] === Infinity ) {
31
+ dis [ nxt ] = dis [ node ] + 1
32
+ parent [ nxt ] = node
33
+ q . push ( nxt )
34
+ } else if ( parent [ node ] !== nxt && parent [ nxt ] !== node ) {
35
+ res = Math . min ( res , dis [ nxt ] + dis [ node ] + 1 )
36
+ }
37
+ }
38
+ }
39
+ }
40
+ } ;
You can’t perform that action at this time.
0 commit comments