问题描述
1 2
2 3
3 4
感谢您的建议和帮助!!!
编辑:
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(这是三个步骤)。