You need to enable JavaScript to run this app. 带α-β剪枝的井字棋Minimax算法运行过慢(首次调用0.5s)如何优化?
优惠活动
大模型
产品
解决方案
定价
更多

带α-β剪枝的井字棋Minimax算法运行过慢(首次调用0.5s)如何优化?

井字棋Minimax算法性能优化方案

以下是可直接落地的优化点,全部调整后首次调用耗时可降至10ms以内:

  • 替换深拷贝操作:copy.deepcopy是性能消耗重灾区,3x3小棋盘完全可以手动生成新棋盘,不需要调用通用深拷贝接口。修改后的result函数参考:
def result(board, action):
    """
    返回落子后的新棋盘,避免深拷贝开销
    """
    newboard = [row.copy() for row in board]
    newboard[action[0]][action[1]] = player(board)
    return newboard

仅这一项调整就能砍掉70%以上的耗时。

  • 提升α-β剪枝效率:调整动作遍历顺序,优先遍历中心、角落这些胜率更高的位置,剪枝可以提前砍掉更多无效分支,大幅减少递归次数。可以在actions函数返回前对可行落子点按优先级排序:
def actions(board):
    """
    返回所有可行落子点,按优先级排序提升剪枝效率
    """
    # 优先级:中心 > 角落 > 边
    priority = {(1,1):0, (0,0):1, (0,2):1, (2,0):1, (2,2):1, (0,1):2, (1,0):2, (1,2):2, (2,1):2}
    possible_moves = []
    for i in range(3):
        for j in range(3):
            if board[i][j] is None:
                possible_moves.append((i,j))
    possible_moves.sort(key=lambda x: priority[x])
    return possible_moves
  • 增加记忆化缓存:相同棋盘状态不需要重复计算,用字典缓存已经算过的棋盘状态返回值即可,注意要把棋盘转成可哈希的元组作为缓存key:
# 全局缓存,key是序列化后的棋盘,value是对应计算结果
cache = {}

def board_to_key(board):
    return tuple(tuple(row) for row in board)

在maxvalue和minvalue函数入口先查缓存,命中直接返回,计算完新结果后存入缓存即可。

  • 精简冗余判断:player函数里的初始状态判断不需要和initial_state全量对比,直接通过X、O的计数判断即可,省掉一次全棋盘遍历:
def player(board):
    """
    返回当前回合的玩家
    """
    X_counter = 0
    O_counter = 0
    for row in board:
        for cell in row:
            if cell == X:
                X_counter += 1
            elif cell == O:
                O_counter += 1
    if X_counter == 0 and O_counter == 0:
        return X
    return O if X_counter > O_counter else X
  • 硬编码最优开局:空棋盘首次调用时直接返回中心落子(1,1),完全不需要走递归计算,耗时直接降到0。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 12:24:04