File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {string[][] } tickets
3
+ * @return {string[] }
4
+ */
5
+ var findItinerary = function ( tickets ) {
6
+ const flight_paths = new Map ( ) ;
7
+ const flight_path_order = [ "JFK" ] ;
8
+
9
+ tickets = tickets . sort ( ) ;
10
+
11
+ for ( const [ source , dest ] of tickets ) {
12
+ let edges = [ ] ;
13
+ if ( flight_paths . has ( source ) ) {
14
+ edges = flight_paths . get ( source ) ;
15
+ }
16
+ edges . push ( dest ) ;
17
+ flight_paths . set ( source , edges ) ;
18
+ }
19
+
20
+ const depth_first_search = ( city ) => {
21
+ if ( flight_path_order . length === tickets . length + 1 ) return true ;
22
+
23
+ const cities_to_go_to = flight_paths . get ( city ) || [ ] ;
24
+ if ( ! cities_to_go_to . length ) return false ;
25
+
26
+ const cities_copied = Array . from ( cities_to_go_to ) ;
27
+
28
+ for ( const other_city of cities_copied ) {
29
+ flight_path_order . push ( other_city ) ;
30
+ cities_to_go_to . shift ( ) ;
31
+
32
+ if ( depth_first_search ( other_city ) ) {
33
+ return flight_path_order ;
34
+ } else {
35
+ flight_path_order . pop ( ) ;
36
+ cities_to_go_to . push ( other_city ) ;
37
+ }
38
+ }
39
+
40
+ return false ;
41
+ } ;
42
+
43
+ return depth_first_search ( "JFK" ) ;
44
+ } ;
You can’t perform that action at this time.
0 commit comments