边数小于n

时间:2018-03-27 21:32:45

标签: python python-3.x undirected-graph

我的数据结构看起来像是一个相当孤立的无向“子图”的图形,并希望得到那些边缘少于N个的子图,在这种情况下只有那些有一个或两个边的子图。我在这里有点迷失,不知道该怎么做。实际上,我存储数据的方式可能不是解决此问题的最佳方法。

例如,对于下面的graph,我想要检索节点A-BH-JK-M,而不是C-G,因为它有更多超过2个边缘。

graph = {  # using sets
    # single (A-B)
    'A': {'B'},
    'B': {'A'},
    # complex (C-G)
    'C': {'D'},
    'D': {'C', 'E'},
    'E': {'D', 'F'},
    'F': {'G', 'E'},
    'G': {'F'},
    # digraph1 (H-J)
    'H': {'J', 'I'},
    'I': {'H'},
    'J': {'H'},
    # digraph2 (K-M)
    'K': {'L'},
    'L': {'K', 'M'},
    'M': {'L'},
}

有关如何在Python中解决此问题的任何想法或建议?

3 个答案:

答案 0 :(得分:1)

您遵循标准算法来关闭图节点:

建立一个方便的新结构。

Pick a starting node however you like; you'll eventually get to all of them.  Put it on the "not visited" list.

While the "not visited" list is not empty:
    Remove the top node from the list.
    Add it to the structure.
    Iterate through its edges.
        If the node on the other end isn't already in the structure,
            add the node and edge to the structure.

现在,只需检查结构中有多少条边。如果它小于3,则表示您需要图表。

从字典中删除这些节点。继续使用新的起点,直到字典为​​空。您现在已经确定了所有小图。

答案 1 :(得分:1)

我不确定您需要多少通用解决方案,所以这是一个非常具体的解决方案,使用networkx package

首先初始化你的图表:

import networkx as nx
edges = [('a','b'),('c','d'),('d','e'),('e','f'),('f','g'),('h','j'),('i','h'),('k','l'),('l','m')]
gr = nx.Graph(edges)

然后找到所有连接的组件并迭代它们:

connected = nx.algorithms.connected_components(gr)
for comp in connected:
    if len(comp) <= 3:
        print(comp)

瞧瞧! (显然你不必打印它们,你可以随心所欲地做它们。)

答案 2 :(得分:1)

您可以在每个节点上进行简单的广度优先搜索,以识别您的子组件。您还可以在执行此操作时计算边数,并将其与子组件一起返回。例如,根据您的图形结构,您可以执行以下操作:

from collections import deque

def bfs(graph, start_node):
    searched = set([start_node])
    edge_count = 0
    queue = deque(start_node)
    while(len(queue)):
        current = queue.popleft()
        for node in graph[current]:
            edge_count += 1                
            if node not in searched:
                searched.add(node)
                queue.append(node)
    return (searched, edge_count/2)

def findSubGraphs(graph):
    subgraphs = []
    found = set()
    for node in graph:
        if node not in found:
            (subgraph, edge_count) = bfs(graph, node)
            found.update(subgraph)
            subgraphs.append((subgraph, edge_count))
    return subgraphs

findSubGraphs(graph)

这应该返回子图的节点和边数的数据结构。例如:

[({'A', 'B'}, 1.0),
 ({'C', 'D', 'E', 'F', 'G'}, 4.0),
 ({'H', 'I', 'J'}, 2.0),
 ({'K', 'L', 'M'}, 2.0)]