最短路徑 II
你已經完成了檢查目標節點是否出現在相鄰節點中的程式碼。接下來,要擴充同一個函式,為目標節點「不」在相鄰節點中的情況撰寫程式碼。
你需要撰寫的程式碼全都在 else 條件裡;也就是當 node2 不在 neighbors 時。
本練習屬於課程
Python 網路分析入門
練習說明
- 使用
.add()方法,將目前的節點node加入集合visited_nodes,用來記錄已造訪的節點。 - 將目前節點
node中尚未被造訪的「相鄰節點」加入queue。為此,你需要結合queue的.extend()方法與串列生成式。.extend()方法會把指定串列中的所有項目接到尾端。- 串列生成式的「輸出運算式」與「迭代變數」都是
n。可迭代物件是neighbors的迭代器,條件是n尚未出現在已造訪的節點中。
- 串列生成式的「輸出運算式」與「迭代變數」都是
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
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 = G.neighbors(node)
if node2 in neighbors:
print('Path exists between nodes {0} and {1}'.format(node1, node2))
return True
else:
# Add current node to visited nodes
____
# Add neighbors of current node that have not yet been visited
queue.extend([____ for ____ in ____ if ____ not in ____])