我有一個模擬圖的大型數據集,其中包含城市以及它們之間的距離。它被存儲爲元組的列表:如何返回第一個有效路徑?
map = [('Baltimore', 'New York City', 85),
('Dallas', 'Cincinatti', 104),
('Denver', 'Salt Lake City', 91),
('Orlando', 'New York City', 17),
('Orlando', 'San Francisco', 64),
('Seattle', 'Baltimore', 89),
('Seattle', 'Portland', 44),
('Portland', 'Las Vegas', 32),
('Las Vegas', 'Reno', 7),
('Reno', 'Chicago', 29),
('Chicago', 'San Francisco', 56)]
這表明頂點兩者之間的「巴爾的摩」和「紐約城」有我試圖用深度優先搜索和寫入的方法85的距離可以採取一個起點城市和一個最終城市,並返回一條有效路徑(如果存在或存在多條路徑),將連接兩條路徑和總距離。例如,如果start_city ='Baltimore'和end_city ='San Francisco',它將打印:YES,巴爾的摩,紐約市,奧蘭多,舊金山,166。我需要的是我的代碼返回是一條有效的路徑總距離。
def dfs_helper(map, start_city, end_city):
stack = []
visited = []
adj_cities = get_connections(map, start_city)
dfs_visit(map, start_city, end_city, adj_cities, stack, visited)
def dfs_visit(results, start_city, end_city, adj_cities, stack, visited):
#mark start_city as visited
visited.append(start_city)
if(end_city in visited): #soon as end_city is discovered, return the path it took to get there.
return stack
for adj_city in adj_cities:
#add adj_city to stack to keep track of that path to the end_city
stack.append(adj_city)
if adj_city not in visited:
adj_cities = get_connections(results, adj_city)
dfs_visit(map, adj_city, end_city, adj_cities, stack, visited)
def get_connections(map, city):
connections = []
for result in map:
if (result[0] == city):
connections.insert(0, result[1])
elif (result[1] == city and result[0] != city):
connections.insert(0, result[0])
connections.reverse()
return connections
我這樣稱呼它:dfs_helper(map, "Baltimore", "San Francisco")
'有時甚至不會返回結果,因爲數據集太大'。那麼,你的數據集有多少個連接?超過10^9嗎? –
構建加權[圖](https://www.python.org/doc/essays/graphs/)來建模對象並使用[圖遍歷算法](http://stackoverflow.com/questions/1072964/names圖遍歷算法)找到你的路徑。 –
@SakibAhammed可能有大約2000個連接。當我到達超過3個城市的路徑時,此代碼將不再運行。 –