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

CS50AI扫雷代码运行6步后耗尽PC资源崩溃,求修复方案

CS50AI扫雷代码崩溃问题排查与修复

问题根源分析

代码崩溃的核心原因是知识库(self.knowledge)无限膨胀,每次调用add_knowledge都会生成大量重复/无效语句,导致内存占用急剧上升,最终耗尽系统资源。具体问题点如下:

1. 子集推断逻辑的严重错误

在add_knowledge的第5步中存在两个致命问题:

  • 直接修改原语句的cells集合:sen1.remove(rem)会破坏原有知识的正确性,污染原始数据。
  • 重复生成无效语句:双重循环遍历知识库副本时,会对同一对语句多次生成相同推断,且未做去重,导致知识库短时间内爆炸式增长。

2. 边界判断错误

生成新语句的邻居遍历中,边界判断条件错误:j > vertical_boundary和i > horizontal_boundary应该改为j >= vertical_boundary和i >= horizontal_boundary(索引从0开始,宽度/高度是最大索引+1),这会导致错误将边界外单元格加入推断,产生无效语句。

3. make_safe_move逻辑错误

该函数在遇到第一个不符合条件的单元格时就返回None,而非遍历所有安全单元格,导致AI无法找到可用安全移动,被迫更早进入随机移动,间接加速知识库膨胀。


修复方案

1. 修复子集推断逻辑

修改add_knowledge中第5步代码,确保不修改原语句、去重并跳过无效语句:

#5) add any new sentences to the AI's knowledge base if they can
# be inferred from existing knowledge

knowledge_copy = self.knowledge.copy()
new_sentences = []
for sentence1 in knowledge_copy:
    for sentence2 in knowledge_copy:
        if sentence1 == sentence2:
            continue
        sen1 = sentence1.cells
        sen2 = sentence2.cells
        if sen2.issubset(sen1):
            # 创建新集合,不修改原语句数据
            new_cells = sen1 - sen2
            new_count = sentence1.count - sentence2.count
            # 跳过空集合,且避免重复添加已有语句
            if new_cells and Sentence(new_cells, new_count) not in self.knowledge + new_sentences:
                new_sentences.append(Sentence(new_cells, new_count))
# 批量添加去重后的新语句
self.knowledge.extend(new_sentences)

2. 修复边界判断错误

修改add_knowledge中邻居遍历的条件:

# 原错误条件
# if j < 0 or j > vertical_boundary or i < 0 or i > horizontal_boundary or (i,j) == cell:
# 修复后
if j < 0 or j >= vertical_boundary or i < 0 or i >= horizontal_boundary or (i,j) == cell:
    continue

3. 修复make_safe_move逻辑

让函数遍历所有安全单元格,找到第一个符合条件的移动:

def make_safe_move(self):
    """
    Returns a safe cell to choose on the Minesweeper board.
    The move must be known to be safe, and not already a move
    that has been made.

    This function may use the knowledge in self.mines, self.safes
    and self.moves_made, but should not modify any of those values.
    """
    for move in self.safes:
        if move not in self.moves_made and move not in self.mines:
            return move
    # 遍历完所有安全单元格后再返回None
    return None

4. 可选优化:清理无效语句

定期从知识库中移除空集合的语句,减少内存占用:

# 在add_knowledge函数的末尾添加
self.knowledge = [s for s in self.knowledge if s.cells]

验证修复效果

修复后,每次调用add_knowledge时,知识库只会添加必要的、不重复的推断语句,内存占用将保持稳定,不会出现资源耗尽的情况,AI可以正常完成更多次操作直至游戏结束。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 00:00:04