開始使用免費開始

最短路徑 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 ____])
編輯並執行程式碼