最短路徑 III
這是這一組練習的最後一題!現在你要完成題目:當兩個節點之間沒有路徑時,寫出會回傳 False 的程式碼。
本練習屬於課程
Python 網路分析入門
練習說明
- 檢查佇列是否已經被清空。你可以用
[-1]檢查佇列最後一個元素。 - 放上適當的 return 敘述,用來表示這兩個節點之間是否存在路徑。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
def path_exists(G, node1, node2):
"""
This function checks whether a path exists between two nodes (node1, node2) in graph G.
"""
visited_nodes = set()
queue = [node1]
for node in queue:
neighbors = list(G.neighbors(node))
if node2 in neighbors:
print('Path exists between nodes {0} and {1}'.format(node1, node2))
return True
break
else:
visited_nodes.add(node)
queue.extend([n for n in neighbors if n not in visited_nodes])
# Check to see if the final element of the queue has been reached
if node == ____:
print('Path does not exist between nodes {0} and {1}'.format(node1, node2))
# Place the appropriate return statement
return ____