You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Python的BFS算法代码添加访问节点计数器?

给BFS算法添加访问节点计数器的实现方法

我是Python新手,现有如下BFS算法代码,该代码可打印已访问节点:

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

visited = [] # List to keep track of visited nodes.
queue = []     #Initialize a queue

def bfs(visited, graph, node):
  visited.append(node)
  queue.append(node)

  while queue:
    s = queue.pop(0)
    print (s, end = " ")

    for neighbour in graph[s]:
      if neighbour not in visited:
        visited.append(neighbour)
        queue.append(neighbour)


# Driver Code
bfs(visited, graph, 'A')

我需要添加一个计数器来统计已访问节点的数量,请问该如何实现?


给你两种简单直观的实现方式,适合新手理解:

方法一:利用visited列表的长度(最省事)

visited列表本身就存储了所有已访问过的节点,直接用len(visited)就能得到节点总数,不需要额外维护计数器。

修改后的代码:

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

visited = [] # List to keep track of visited nodes.
queue = []     #Initialize a queue

def bfs(visited, graph, node):
  visited.append(node)
  queue.append(node)

  while queue:
    s = queue.pop(0)
    print (s, end = " ")

    for neighbour in graph[s]:
      if neighbour not in visited:
        visited.append(neighbour)
        queue.append(neighbour)

# Driver Code
bfs(visited, graph, 'A')
# 打印已访问节点总数
print("\n已访问节点总数:", len(visited))

方法二:单独维护计数器变量(支持实时跟踪)

如果需要在遍历过程中随时查看当前已访问的节点数,可以单独定义一个计数器,每次新增访问节点时递增计数。

修改后的代码:

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

visited = [] # List to keep track of visited nodes.
queue = []     #Initialize a queue

def bfs(visited, graph, node):
  visited.append(node)
  queue.append(node)
  count = 1  # 初始节点已访问,计数从1开始

  while queue:
    s = queue.pop(0)
    print(s, end = " ")
    # 可选:实时打印当前计数
    # print(f" | 当前已访问{count}个节点")

    for neighbour in graph[s]:
      if neighbour not in visited:
        visited.append(neighbour)
        queue.append(neighbour)
        count += 1  # 每新增一个访问节点,计数加1
  return count  # 返回总计数

# Driver Code
total_count = bfs(visited, graph, 'A')
print("\n已访问节点总数:", total_count)

内容的提问来源于stack exchange,提问作者chaei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 00:25:26