File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number[][] } routes
3
+ * @param {number } S
4
+ * @param {number } T
5
+ * @return {number }
6
+ */
7
+ const numBusesToDestination = function ( routes , S , T ) {
8
+ if ( S === T ) return 0
9
+ const map = { }
10
+ const visited = new Array ( routes . length ) . fill ( false ) ,
11
+ queue = [ S ]
12
+ let rides = 0
13
+ for ( let i = 0 ; i < routes . length ; i ++ ) {
14
+ for ( const stop of routes [ i ] ) {
15
+ if ( map [ stop ] === undefined ) {
16
+ map [ stop ] = [ ]
17
+ }
18
+ map [ stop ] . push ( i )
19
+ }
20
+ }
21
+ while ( queue . length > 0 ) {
22
+ let size = queue . length
23
+ rides += 1
24
+ while ( size > 0 ) {
25
+ const currStop = queue . shift ( )
26
+ size -= 1
27
+ for ( const bus of map [ currStop ] ) {
28
+ if ( visited [ bus ] ) continue
29
+ visited [ bus ] = true
30
+ for ( const stop of routes [ bus ] ) {
31
+ if ( stop === T ) return rides
32
+ queue . push ( stop )
33
+ }
34
+ }
35
+ }
36
+ }
37
+ return - 1
38
+ }
You can’t perform that action at this time.
0 commit comments