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

在2D列表中识别围棋被包围棋子组的技术实现问题

围棋死棋识别与清除解决方案

核心逻辑

围棋中,死棋的判定标准是某一颜色的棋子组完全没有气(相邻的空点)。正确的处理方式是针对每一组同色棋子,计算其相邻的空点数量,若气数为0则清除该组棋子。

实现步骤

  • 遍历棋盘所有点位,标记未被访问的棋子(1或2)
  • 对每个未访问的棋子,用BFS遍历整个同色棋子组,同时统计该组周围的空点(气)数量
  • 若气数为0,将该组所有棋子置为0
  • 同时支持黑白双方棋子的死棋判定

完整代码实现

def clear_dead_groups(board):
    rows = len(board)
    cols = len(board[0]) if rows > 0 else 0
    visited = [[False for _ in range(cols)] for _ in range(rows)]
    directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]  # 上下左右四个方向

    for i in range(rows):
        for j in range(cols):
            if board[i][j] != 0 and not visited[i][j]:
                current_color = board[i][j]
                group = []
                has_liberty = False
                queue = [(i, j)]
                visited[i][j] = True

                # BFS遍历整个同色棋子组
                while queue:
                    x, y = queue.pop(0)
                    group.append((x, y))

                    # 检查四个方向的气和同色棋子
                    for dx, dy in directions:
                        nx = x + dx
                        ny = y + dy
                        if 0 <= nx < rows and 0 <= ny < cols:
                            if board[nx][ny] == 0:
                                has_liberty = True
                            elif board[nx][ny] == current_color and not visited[nx][ny]:
                                visited[nx][ny] = True
                                queue.append((nx, ny))

                # 无气则清除该组棋子
                if not has_liberty:
                    for x, y in group:
                        board[x][y] = 0
    return board

测试案例

输入棋盘

test_board = [
    [0, 2, 2, 0, 0],
    [2, 1, 1, 2, 0],
    [2, 2, 1, 2, 0],
    [0, 0, 2, 0, 0],
    [0, 0, 0, 0, 0]
]

处理后输出

result = clear_dead_groups(test_board)
for row in result:
    print(row)
# 输出结果:
# [0, 2, 2, 0, 0]
# [2, 0, 0, 2, 0]
# [2, 2, 0, 2, 0]
# [0, 0, 2, 0, 0]
# [0, 0, 0, 0, 0]

关键说明

  • 方案通过从棋子组出发遍历,直接统计气的数量,避免了从空点flood fill被活棋阻挡的问题
  • 支持任意大小的棋盘,同时处理黑白双方的死棋
  • BFS遍历确保不会遗漏任何同色棋子组,visited矩阵防止重复处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 16:47:09