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

如何在网格中查找并统计存活邻居?代码求助

如何实现countLiveNeighbors函数统计存活邻居数

我需要编写一个countLiveNeighbors函数,计算网格中指定单元格周围的所有邻居,且仅统计值为1的“存活邻居”,不能包含中间单元格本身。查阅论坛后仍有困惑,附上现有代码,希望有人讲解实现步骤并修正代码。

现有代码

def countLiveNeighbors( grid, rowIndex, columnIndex ):
    # TODO - Find the number of grid rows (HINT: use the len() of the grid)

    rows = len(grid)
    
    # TODO - Find the number of grid columns (HINT: use the len() of the first row)

    cols = len(grid[0])

    # TODO - Compute neighbor indices.
    #        Make sure all indices are positive!
    #        Make sure all indices are not too large!
    r = rowIndex
    c = columnIndex
    for row in rows:
        for col in cols:
            if col >= 0:
               grid[r][c] + 1
            else:
                grid[r][c] - 1
    # TODO - Count the number of live neighbors.
    #        Do NOT count the cell in the middle, only neighbors!


    # TODO - Return the number of live neighbors




# make a test grid to test you function on
testGrid = [[0,0,0,0,0],
            [0,1,1,0,0],
            [0,1,1,0,0],
            [0,0,0,0,0]]


# count the live neighbors for a cell at some row and column
row = 1
col = 2

neighborCount = life_module.countLiveNeighbors( testGrid, row, col )

print( "cell at row", row, "and col", col, "has", neighborCount, "live neighbors" )

实现步骤拆解

  1. 确定网格边界:先获取网格的总行数和总列数,避免访问超出范围的索引。
  2. 遍历邻居范围:每个单元格最多有8个邻居(上下左右+四个对角线),需要遍历目标单元格周围的3×3区域,但要排除自身。
  3. 验证索引合法性:确保邻居的行号和列号在0 ≤ 索引 < 总行数/总列数范围内,防止索引越界报错。
  4. 统计存活邻居:对每个合法的邻居,判断其值是否为1,累加符合条件的数量。

修正后的代码

def countLiveNeighbors(grid, rowIndex, columnIndex):
    # 获取网格的总行数和总列数
    rows = len(grid)
    cols = len(grid[0]) if rows > 0 else 0
    count = 0

    # 遍历目标单元格周围的3×3偏移量(覆盖所有8个邻居+自身)
    for dr in [-1, 0, 1]:
        for dc in [-1, 0, 1]:
            # 跳过中间的自身单元格
            if dr == 0 and dc == 0:
                continue
            # 计算邻居的实际索引
            neighbor_row = rowIndex + dr
            neighbor_col = columnIndex + dc
            # 检查索引是否在合法范围内
            if 0 <= neighbor_row < rows and 0 <= neighbor_col < cols:
                # 若为存活细胞则计数+1
                if grid[neighbor_row][neighbor_col] == 1:
                    count += 1

    return count


# 测试用例
testGrid = [[0,0,0,0,0],
            [0,1,1,0,0],
            [0,1,1,0,0],
            [0,0,0,0,0]]

row = 1
col = 2

# 修正原代码中未定义的life_module调用问题
neighborCount = countLiveNeighbors(testGrid, row, col)

print(f"cell at row {row} and col {col} has {neighborCount} live neighbors")

关键修正说明

  • 替换了错误的循环逻辑:原代码直接遍历行数/列数数值,改为遍历[-1,0,1]偏移量,精准覆盖所有邻居位置。
  • 添加索引合法性检查:避免访问网格外的无效位置,防止运行时错误。
  • 排除自身单元格:通过判断偏移量均为0的情况,跳过目标单元格本身。
  • 初始化并累加计数:新增count变量统计存活邻居数量,最终返回该值。
  • 修正测试代码:移除未定义的life_module调用,直接调用函数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 17:02:30