-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtravel.py
More file actions
25 lines (23 loc) · 758 Bytes
/
travel.py
File metadata and controls
25 lines (23 loc) · 758 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def main():
data = [['A','B'],['G','H'],['A','G'],['H','K'],['K','F'],['F','X'],['G','X'],['B','K']]
myMap = {}
for node in data:
myMap[node[0]] = myMap.get(node[0],[])+[node[1]]
myMap[node[1]] = myMap.get(node[1],[])+[node[0]]
start = 'A'
end = 'X'
shortestPath = bfs(myMap,start,end)
print(' '.join(shortestPath))
#找到點對點最小的路徑
def bfs(myMap,start,end):
quene = [[start]]
while quene:
nowPath = quene.pop(0)
lastNode = nowPath[-1]
if lastNode == end:
return nowPath
for nextNode in myMap[lastNode]:
if nextNode in nowPath:
continue
quene.append(nowPath+[nextNode])
main()