The code below brute force creates a graph of cities and then runs it through a DFS to find the shortest path. The result I get is different whether I use 'visited.append(node)' or 'visited=visited + [node]'. Appending to the list is incorrect does not find the shortest path.
The print within the DFS is to debug why there is a difference, but I cannot determine what the difference is. Can anyone explain this detail to me? Thanks!
def CreateGraph(cities):
g={}
for city in cities:
g[city]=[]
return g
def AddRouteToGraph(g,src,dest):
if src in g and dest in g:
g[src].append(dest)
else:
raise ValueError
cities=['Bmore', 'DC', 'SanFran', 'Philly', 'Seattle', 'NYC']
g=CreateGraph(cities)
AddRouteToGraph(g,'Bmore','Seattle')
AddRouteToGraph(g,'Bmore','Philly')
AddRouteToGraph(g,'Philly','NYC')
AddRouteToGraph(g,'DC','NYC')
AddRouteToGraph(g,'SanFran','Philly')
AddRouteToGraph(g,'SanFran','DC')
AddRouteToGraph(g,'SanFran','Seattle')
AddRouteToGraph(g,'Seattle','DC')
def DFS_shortest(g,node,dest,visited,shortest):
visited.append(node)
#visited=visited + [node]
print(f'visited={visited} of type {type(visited)}')
if node==dest:
return visited
for city in g[node]:
if city not in visited:
if shortest!=None:
print(city, str(len(visited)), str(len(shortest)))
else:
print(city, str(len(visited)), 'None')
if shortest==None or len(visited)<len(shortest):
newPath=DFS_shortest(g,city,dest,visited,shortest)
if newPath!=None:
shortest=newPath
return shortest
print(DFS_shortest(g,'Bmore','NYC',[],None))