python实现广度优先搜索_Python实现广度优先搜索

通过首先将级别0指定给开始节点,可以跟踪每个节点的级别。然后为节点的每个邻居X分配级别level_of_X + 1。

另外,您的代码将同一个节点多次推入队列。我使用了一个单独的列表visited来避免这种情况。# sample graph implemented as a dictionary

graph = {'A': ['B', 'C', 'E'],

'B': ['A','D', 'E'],

'C': ['A', 'F', 'G'],

'D': ['B'],

'E': ['A', 'B','D'],

'F': ['C'],

'G': ['C']}

# visits all the nodes of a graph (connected component) using BFS

def bfs_connected_component(graph, start):

# keep track of all visited nodes

explored = []

# keep track of nodes to be checked

queue = [start]

levels = {} # this dict keeps track of levels

levels[start]= 0 # depth of start node is 0

visited= [start] # to avoid inserting the same node twice into the queue

# keep looping until there are nodes still to be checked

while queue:

# pop shallowest node (first node) from queue

node = queue.pop(0)

explored.append(node)

neighbours = graph[node]

# add neighbours of node to queue

for neighbour in neighbours:

if neighbour not in visited:

queue.append(neighbour)

visited.append(neighbour)

levels[neighbour]= levels[node]+1

# print(neighbour, ">>", levels[neighbour])

print(levels)

return explored

ans = bfs_connected_component(graph,'A') # returns ['A', 'B', 'C', 'E', 'D', 'F', 'G']

print(ans)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值