通过长度路径返回python文件中的节点数

问题描述

我对项目的最后一个问题在python中遇到了一个难题。

想象一下,您得到一个类似的文件

1 2
2 3
3 4
  • 如果节点1通过一条边链接到节点2,则2可以通过长度为1的路径(从1:1-2)访问

  • 如果1链接到2本身链接到3且自身链接到4,则可以通过长度为1的路径1:1-2-3-4访问4

  • 我想通过认的长度为3的路径返回从给定节点可访问的节点数

感谢您的建议和帮助!!!

编辑:

def bfs(graph,start_node,distance):
    if distance == 0:
        return [start_node]
    visited = []
    queue = []
    nodes_at_dist = []

    level = 0
    visited.append(start_node)
    queue.append((start_node,level))

解决方法

首先,我们重建数据结构以简化查找,即可以访问哪些节点。我认为我们的图是无向的。

graph = [(1,2),(2,3),(3,4),(1,6),(6,7)]

# we restructure our input to simplify the lookup
graph_dict = {}
for n1,n2 in graph:
    if n1 not in graph_dict:
        graph_dict[n1] = set()
    if n2 not in graph_dict:
          graph_dict[n2] = set()
    graph_dict[n1].add(n2)
    graph_dict[n2].add(n1)

因此,我们有一个dict,其中的键是所有现有节点,而对应的值是一组直接连接的所有节点:

{1: {2,4},2: {1,3,6},3: {2,4: {1,3},6: {2,7},7: {6}}

下一部分本质上是我们的方法,该方法根据固定距离查找可到达的节点:

def bfs(graph_dict,start_node,distance):
    # We reached the end and return the current node
    if distance == 0:
        return {start_node}
        
    # We look-up all nodes which are reachable with one step
    reachable = graph_dict[start_node]
        
    # Now we iterate through this set and call our method again (recursively)
    result=set()
    for node in reachable:
        tmp=bfs(graph_dict,node,distance-1)
        result=result.union(tmp)
    return result 

示例输出1:距离= 2,start_node = 1

{1,6}

请注意,我们的结果集中包含“ 1”,因为我们可以步行1-2-1(这是两个步骤)。

示例输出2:distance = 3,start_node = 1

{2,4,7}

请注意,我们的结果集中包含“ 2”,因为我们可以走1-2-1-2(这是三个步骤)。