如何在网格中查找邻居

How to find neighbors in a grid

提问人:TRNF 提问时间:10/12/2023 最后编辑:TRNF 更新时间:10/12/2023 访问量:57

问:

我必须创建一个函数来计算网格中给定单元格周围的所有邻居。不仅如此,它还必须返回所有等于 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" )

我不明白我会采取什么步骤来寻找邻居,并只计算活着的邻居。如果有人可以解释它是如何完成的以及纠正我的代码,我将不胜感激。

Python 函数 循环多 维数组

评论

0赞 001 10/12/2023
通常最好用一种语言标记您的问题。蟒蛇?您可以编辑问题并添加标签。
0赞 TRNF 10/12/2023
好的,我标记了它。谢谢

答:

0赞 PlsBuffMyBrain 10/12/2023 #1

给定某个单元格,对应于上、下、左、右邻居的位置是 、 和 。如果需要对角线邻居,那么应该很容易根据4个方向找出它们的索引。显然,您必须检查索引是否在数组的边界内,这可以通过 来完成。grid[r][c]grid[r - 1][c]grid[r + 1][c]grid[r][c - 1]grid[r][c + 1]r in range(rows) and c in range(cols)

执行此操作的代码如下所示:

def countLiveNeighbors( grid, rowIndex, columnIndex):
    rows = len(grid)
    cols = len(grid[0])
    r, c = rowIndex, columnIndex
    live_count = 0
    #Coordinates corresponding to up, down, left, right
    dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)] 
    for x, y in dirs: 
        new_r, new_c = r + x, c + y
        if new_r in range(rows) and new_c in range(cols) and grid[new_r][new_c] == 1:
            live_count += 1
            
    return live_count

# 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" )

这将输出 .同样,如果对角线方向算作邻居,则必须将它们添加到 中。cell at row 1 and col 2 has 2 live neighborsdirs

评论

0赞 TRNF 10/12/2023
好的,谢谢!不过,我有一个快速的问题,我将如何在代码中实现您的边界检查?我是否必须创建另一个函数,或者有没有办法在原始函数中编写它?
0赞 PlsBuffMyBrain 10/12/2023
@TRNF 编辑了我的答案并更新了它以显示代码。