Untitled
unknown
python
2 years ago
1.1 kB
9
Indexable
def ShortestPath(strArr):
places = {}
nPlaces = int(strArr[0])
for i in range(1, nPlaces + 1):
places[strArr[i]] = {
'name': strArr[i],
'path': '',
'routes': {}
}
for i in range(nPlaces + 1, len(strArr)):
route = strArr[i].split('-')
places[route[0]]['routes'][route[1]] = places[route[1]]
places[route[1]]['routes'][route[0]] = places[route[0]]
start = places[strArr[1]]
finish = places[strArr[nPlaces]]
start['path'] = start['name']
pending = [start]
while pending:
here = pending.pop(0)
if here == finish:
return finish['path']
for place in here['routes']:
if here['routes'][place]['path'] == '':
next_place = here['routes'][place]
next_place['path'] = here['path'] + '-' + next_place['name']
pending.append(next_place)
return -1
# Example usage
import sys
print ShortestPath(sys.stdin.readline().split())
Editor is loading...
Leave a Comment