【问题标题】:Graph challenge: Get adjacency list from list of children nodes图挑战:从子节点列表中获取邻接列表
【发布时间】:2014-04-17 05:45:21
【问题描述】:

我有一个具有以下结构的图表:

{'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']}

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

谢谢!

【问题讨论】:

  • 非常感谢执行此操作的递归算法。谢谢!
  • 当前形式的问题与本网站无关。投票结束。
  • 是否假定它是无向的和无环的?此外,如果您发布您的尝试也会有所帮助,以便我们向您展示如何修复它。我们在这里不仅仅是为你做功课
  • 是的。它是无向的和无环的。
  • @akshitBhatia:My attempts at this have been expensive in terms of space and time。向我们展示您的尝试,我们可以尝试帮助您解决问题

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


【解决方案1】:

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

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    相关资源
    最近更新 更多