@@ -30,35 +30,61 @@ def unroll_shortest_path(current, optimal_parent_map, path=()):
3030 return unroll_shortest_path (optimal_parent_map [current ], optimal_parent_map , (current ,) + path )
3131
3232
33- def get_city_data ():
34- city_data = None
35- with open ("city_data.json" ,"r" ) as f :
36- city_data = json .loads (f .read ())
37- return city_data
33+ def depth_first_search_iter (from_city , to_city , city_data ):
34+ to_visit = [from_city ]
35+ visited = set ([from_city ])
36+ parent_map = {from_city : None }
37+
38+ while to_visit != []:
39+ current = to_visit .pop ()
40+ visited .add (current )
41+ neighbors = city_data [current ].keys ()
42+
43+ for n in neighbors :
44+ if n == to_city :
45+ parent_map [n ] = current
46+ return unroll_shortest_path (to_city , parent_map )
47+
48+ elif n not in visited :
49+ parent_map [n ] = current
50+ to_visit .append (n )
51+
52+ return None
3853
3954
4055def depth_first_search (from_city , to_city , city_data ):
4156 visited = set ()
4257
43- def _depth_first_search (from_city , to_city , city_data , path = ()):
44- print ( "Checking: {}" . format ( from_city ))
58+ def _depth_first_search (from_city , to_city , city_data , path = (from_city , )):
59+ # If destination found, return the path hereto compiled
4560 if from_city == to_city :
4661 return path
47- elif len (visited ) == len (city_data ):
48- print ("HIT" )
49- return None
5062 else :
51- neighbors = list (city_data [from_city ].keys ())
5263 visited .add (from_city )
53- for n in neighbors :
54- if n not in visited :
55- result = _depth_first_search (n , to_city , city_data , path + (n ,))
56- if result is not None :
57- return result
64+ neighbors = city_data [from_city ].keys ()
65+ unvisited_neighbors = [n for n in neighbors if n not in visited ]
66+
67+ # If there are no more unvisited neighbors, this path doesn't lead to the goal
68+ if unvisited_neighbors == []:
69+ return None
70+
71+ # Else, for each unvisited neighbor, recursively try to reach the solution
72+ # from it as the "from_city". Also update the path
73+ for n in unvisited_neighbors :
74+ result = _depth_first_search (n , to_city , city_data , path + (n ,))
75+ if result is not None :
76+ return result
5877
5978 return _depth_first_search (from_city , to_city , city_data )
6079
6180
81+ def get_city_data ():
82+ city_data = None
83+ with open ("city_data.json" ,"r" ) as f :
84+ city_data = json .loads (f .read ())
85+ return city_data
86+
87+
6288if __name__ == '__main__' :
6389 city_data = get_city_data ()
6490 try :
@@ -71,5 +97,6 @@ def _depth_first_search(from_city, to_city, city_data, path=()):
7197 print (" -" , city )
7298 sys .exit (1 )
7399
74- print (depth_first_search (city_from , city_to , city_data ))
100+ print ("Recursive:" , depth_first_search (city_from , city_to , city_data ))
101+ print ("\n Iterative:" , depth_first_search_iter (city_from , city_to , city_data ))
75102
0 commit comments