简体   繁体   English

在python中实现bfs算法

[英]implementation bfs algorithm in python

I have written this piece of code to start a bfs traversal from element x in a given graph(from input) and finally print the number of visited vertices.我已经编写了这段代码来从给定图形(从输入)中的元素 x 开始 bfs 遍历,最后打印访问的顶点数。 but it doesn't work.:( for example for the below input,the right output is 6 but my code prints 3. input:但它不起作用。:( 例如,对于下面的输入,正确的 output 是 6,但我的代码打印 3。输入:

6
1 2
1 3
2 4
3 5
3 6
4 6

在此处输入图像描述

python code python代码

from collections import defaultdict

def make_graph(graph,u,v):
    graph[u].append(v)
def bfs(visited, graph, node):
    output=[]
    visited.append(node)
    queue.append(node)
    while queue:
        node = queue.pop(0)
        output.append(node)
        for nghbr in graph[node]:
            if nghbr not in visited:
                visited.append( nghbr )
                queue.append( nghbr )
    print(len(output))

x='3'
#bfs starts from node x in graph
n=int(input())
#n:number of nodes(number of nodes is equal to number of edges)
graph = defaultdict(list)
visited=[]
queue = []
for i in range (n):
    u,v=input().split()
    make_graph(graph,u,v)

bfs(visited, graph,x)

There are few issuses here:这里有几个问题:

  1. You are using the defaultdict class from the collections module to create a dictionary where all the keys have an empty list as their default value.您正在使用 collections 模块中的 defaultdict class 创建一个字典,其中所有键的默认值都是空列表。 However, you are adding the keys to the dictionary as strings, but you are using them as integers when you call the bfs function.但是,您将键作为字符串添加到字典中,但在调用 bfs function 时将它们作为整数使用。
  2. You are not adding the edges to the graph correctly.您没有正确地将边添加到图形中。
  3. You are using the variable queue to store the nodes to visit, but you are not initializing it before using it.您正在使用变量队列来存储要访问的节点,但在使用它之前没有对其进行初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM