[英]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:这里有几个问题:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.