图挑战:从子节点列表中获取邻接列表

时间:2014-04-17 05:45:22

标签: python algorithm data-structures graph adjacency-list

我的图表具有以下结构:

{'a':['b','c','d','e'],
'b':['d'],
'c':['d','e'],
'd':[],
'e':[],
'f':['i','j','c','e','d'],
'i':['c','e','d']
'j':['e']}

此列表不是邻接列表,因为它包含节点的所有子节点。不是直接的孩子。

该图应该如下所示:

        a       f     
       / \     / \
      b   \   i   j
       \   \ /   /    
        \   c   /
         \ / \ /
          d   e

所以邻接列表如下:

{'a':['b','c'],
'b':['d'],
'c':['d','e'],
'd':[],
'e':[],
'f':['i','j'],
'i':['c'],
'j':['e']}

我需要一个算法才能做到这一点。算法应尽可能快地使用最小额外空间。有谁能解决这个问题?

谢谢!

1 个答案:

答案 0 :(得分:0)

不完全递归,但您可以遍历每个子节点,查找它,并从当前节点中删除它的所有子节点:

def get_adjacency(graph):
    graph = {node: set(children) for node, children in graph.items()}

    for node, children in graph.items():
        for child in children:
            children = children - graph[child]
        graph[node] = children

    return {node: list(children) for node, children in graph.items()}

c = {
    'a': ['b','c','d','e'],
    'b': ['d'],
    'c': ['d','e'],
    'd': [],
    'e': [],
    'f': ['i','j','c','e','d'],
    'i': ['c','e','d'],
    'j': ['e']
}

print get_adjacency(c)