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

Python队列实现BFS出现AttributeError问题求助

问题排查与修复方案

报错核心是执行v.get_adjacent()时,v是None对象,所以要找到v变为None的根源,以下是分步排查和修复:


1. 初始节点获取的有效性校验

你的BFS直接通过self.vertices.head.getValue()获取起始节点,以下几种情况会导致v为None:

  • self.vertices是空链表(比如初始化后未添加任何顶点)
  • self.vertices.head本身为None
  • getValue()返回的是None

修复方案:在获取初始节点前添加校验逻辑:

def BFS(self):
    t = SNQ.DSAQueue()
    q = SNQ.DSAQueue()

    # 标记所有顶点为未访问
    for node in iter(self.vertices):
        if node is not None:
            node.set_visited(False)

    # 新增初始节点有效性校验
    if not self.vertices or self.vertices.head is None:
        print("图中无可用顶点")
        return
    v = self.vertices.head.getValue()
    if v is None:
        print("起始顶点无效")
        return
    
    v.set_visited(True)  # 起始节点入队前需标记为已访问,避免重复处理
    print(type(v))
    print('Start:', v.get_name())
    print(type(v))
    q.enqueue(v)

    # 后续循环代码...

2. get_vertex()返回值的非空校验

遍历邻接列表时,w = self.get_vertex(value)如果找不到对应顶点,可能返回None,若将None入队,后续出队后调用get_adjacent()就会触发报错。

修复方案:使用w前先做非空判断:

adj_list = v.get_adjacent()
for value in adj_list:
    w = self.get_vertex(value)
    # 先确保w是有效顶点,再检查访问状态
    if w is not None and not w.get_visited():
        w.set_visited(True)
        t.enqueue(w)
        q.enqueue(w)

3. 队列实现的正确性检查

确认SNQ.DSAQueue的核心方法是否正常工作:

  • enqueue是否真的将完整对象存入队列,有没有出现存储丢失导致对象变为None的情况
  • dequeue在队列空时是否返回None?如果是,需确保is_empty()方法能准确判断队列状态,避免出队None

可以临时添加调试打印,验证入队/出队的对象:

# 入队前打印
print(f"入队对象: {v}")
q.enqueue(v)

# 出队后打印
v = q.dequeue()
print(f"出队对象: {v}")
adj_list = v.get_adjacent()

4. 优化get_adjacent()的冗余判断

看你的get_adjacent代码,当self.count为0时,np.empty(0, dtype=object)会返回空数组而非None,所以原代码里的if adj_list is not None:是多余的,可以直接删除,空数组的遍历不会执行,不影响逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 02:55:12