簡體   English   中英

根據給定的鄰接矩陣,找到兩個圖的交集和並集?

[英]Finding the Intersection and Union of two graphs given their adjacency matrices?

給定兩個鄰接矩陣:

graph1 = [[0, 1, 2, 1, 9], [1, 0, 0, 6, 0], [2, 0, 0, 15, 2], [1, 6, 15, 0, 7], [9, 0, 2, 7, 0]]
graph2 = [[0, 19, 1, 0, 12, 0], [19, 0, 2, 0, 0, 0], [1, 2, 0, 0, 2, 0], [0, 0, 0, 0, 3, 5], [12, 0, 2, 3, 0, 2], [0, 0, 0, 5, 2, 0]]

如何找到他們的交集以及他們的聯合

->具有最高值的邊緣將作為所選的結果圖形邊緣。

路口:

鄰接矩陣中兩個鄰接矩陣的交集,其中在每個原始矩陣中連接了兩個節點。

在這種情況下,您必須選擇具有最高值的邊。

def graph_intersection(graph1, graph2):
    """calculates the intersection of two graphs represented by their adjacency matrices
    the edges with highest weights are retained.
    :graph1: List of Lists representing the adjacency matrix of a graph
             graph1 is not mutated by the function
    :graph2: List of Lists representing the adjacency matrix of a graph
             graph2 is not mutated by the function
    :returns: a newly constructed List of Lists representing the intersection of graph1 and graph2
    """
    intersection = []
    for g1, g2 in zip(graph1, graph2):
        line = []
        for e1, e2 in zip(g1, g2):
            line.append(max(e1, e2) if e1 and e2 else 0)
        intersection.append(line)
    return intersection

print(graph_intersection(graph1, graph2))

輸出:

[[0, 19, 2, 0, 12], [19, 0, 0, 0, 0], [2, 0, 0, 0, 2], [0, 0, 0, 0, 7], [12, 0, 2, 7, 0]]

聯盟:

聯合涉及更多,但可以使用itertools.zip_longest獲得:

import itertools

def graph_union(graph1, graph2):
    """calculates the union of two graphs represented by their adjacency matrices
    the edges with highest weights are retained.
    :graph1: List of Lists representing the adjacency matrix of a graph
             graph1 is not mutated by the function
    :graph2: List of Lists representing the adjacency matrix of a graph
             graph2 is not mutated by the function
    :returns: a newly constructed List of Lists representing the union of graph1 and graph2
    """
    union = []
    for g1, g2 in itertools.zip_longest(graph1, graph2):
        line = []
        g1 = g1 if g1 is not None else (0,)
        g2 = g2 if g2 is not None else (0,)
        for e1, e2 in itertools.zip_longest(g1, g2):
            e1 = e1 if e1 is not None else 0
            e2 = e2 if e2 is not None else 0
            line.append(max(e1, e2))
        union.append(line)
    return union

graph1 = [[0, 1, 2, 1, 9], [1, 0, 0, 6, 0], [2, 0, 0, 15, 2], [1, 6, 15, 0, 7], [9, 0, 2, 7, 0]] 
graph2 = [[0, 19, 1, 0, 12, 0], [19, 0, 2, 0, 0, 0], [1, 2, 0, 0, 2, 0], [0, 0, 0, 0, 3, 5], [12, 0, 2, 3, 0, 2], [0, 0, 0, 5, 2, 0]]

print(graph_intersection(graph1, graph2))
print(graph_union(graph1, graph2))

輸出:

[[0, 19, 2, 1, 12, 0], [19, 0, 2, 6, 0, 0], [2, 2, 0, 15, 2, 0], [1, 6, 15, 0, 7, 5], [12, 0, 2, 7, 0, 2], [0, 0, 0, 5, 2, 0]]

暫無
暫無

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

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