簡體   English   中英

從 python 中的鄰接矩陣計算距離矩陣

[英]Computing the distance matrix from an adjacency matrix in python

編寫從圖(圖論)生成距離矩陣的代碼,該代碼應使用鄰接矩陣並且不能使用 NetworkX 模塊中的任何函數,除了 .networkx.adjacency_matrix()。

我了解距離矩陣如何工作的過程。 我關於如何涉及鄰接矩陣的理論是它采用連接兩個節點的元素並增加距離。 例如,假設我有節點 A、B 和 C。A 連接到 B,B 連接到 C。兩個連接節點之間的距離為 1。因此從 A 到 C 的距離為 2。

我唯一的問題是如何將其實現到代碼中,以便它為任何給定的圖形創建一個距離矩陣。

感謝您的幫助,如果我的解釋不清楚,請抱歉,如果您希望我澄清任何事情,請告訴我。

檢查以下代碼是否有幫助。

#G is a networkX graph.
def get_actual_distance_between_two_nodes(G, i, j):
    pos=nx.spring_layout(G, seed=random_seed)
    sp = nx.shortest_path(G, i, j)
    edges_set = [[sp[i], sp[i+1]] for i in range(len(sp)-1)]

    distance_list = []
    for edge in edges_set:
        start_node = edge[0]
        end_node = edge[1]

        x1 = pos[start_node][0]
        y1 = pos[start_node][1]
        x2 = pos[end_node][0]
        y2 = pos[end_node][1]

        distance = math.dist([x1,y1], [x2,y2])
        distance_list.append(distance)

    return (sum(distance_list)) 
    
def nodes_connected(G, u, v):
    return u in G.neighbors(v)

def create_distance_matrix(G, nodes_list):
    distance_matrix_custom = []
    for i in range(len(nodes_list)):
        current_node = nodes_list[i]
        #print("Current Node: --->", current_node)
        list_of_distance = []
        for j in range(len(nodes_list)):
            target_node = nodes_list[j]
            #print("Target Node: --->", target_node)
            
            if(current_node == target_node):
                actual_distance = 0
            elif(G.has_edge(current_node, target_node)):
                actual_distance = get_actual_distance_between_two_nodes(G, current_node, target_node)                
            else:
                #actual_distance = float('inf')
                actual_distance = 10000000000
            list_of_distance.append(actual_distance)
        distance_matrix_custom.append(list_of_distance)

    return distance_matrix_custom
        
distance_matrix_custom = create_distance_matrix(G, nodes_list)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM