NxN 数组检查邻居单元格

NxN array check neighbors cells

我有一个 NxN 数组 (t_field),其中的单元格填充了 0 或 1。

我想检查范围内实体的任何邻居是否已填充。

实体是一个 1 的序列,有 (row, start), (row, end),我想检查上面的行,下面的行,但在 start-1 和 end + 的约束范围内1:

contacts = [t_field[row_n - 1][start-1:end+2], 
            t_field[row_n + 1][start-1:end+2]]

但是如果我在第 0 行,我不希望它检查第 1 行,因为这会查看网格的末尾。在那种情况下,它只会检查第 1 行;反之亦然,如果 row 是 n(网格的大小),它会在检查 row+1

时 trow 和 IndexError

start/end也是如此,如果开始是 0 我不想检查 -1,因为它会查看网格的另一侧。我只想检查结束+2。反之亦然。

start = column_n - length + 1
end = column_n

upperrow = row_n - 1
lowerrow = row_n + 1

if upperrow < 0:
    upperrow = None
if lowerrow >= len(t_field):
    lowerrow = None

leftside = start - 1
rightside = end + 2
if leftside < 0:
    leftside = None
if rightside >= len(t_field):
    rightside = None

if upperrow is not None and lowerrow is not None:
    if leftside is not None and rightside is not None:
        contacts = [t_field[upperrow][leftside:rightside],
                    t_field[lowerrow][leftside:rightside]]
    elif leftside is None and rightside is not None:
        contacts = [t_field[upperrow][0:rightside],
                    t_field[lowerrow][0:rightside]]
    elif leftside is not None and rightside is None:
        contacts = [t_field[upperrow][leftside:end + 1],
                    t_field[lowerrow][leftside:end + 1]]
elif upperrow is None and lowerrow is not None:
    if leftside is not None and rightside is not None:
        contacts = [t_field[lowerrow][leftside:rightside]]
    elif leftside is None and rightside is not None:
        contacts = [t_field[lowerrow][0:rightside]]
    elif leftside is not None and rightside is None:
        contacts = [t_field[lowerrow][leftside:end + 1]]
elif upperrow is not None and lowerrow is None:
    if leftside is not None and rightside is not None:
        contacts = [t_field[upperrow][leftside:rightside]]
    elif leftside is None and rightside is not None:
        contacts = [t_field[upperrow][0:rightside]]
    elif leftside is not None and rightside is None:
        contacts = [t_field[upperrow][leftside:end + 1]]

if any(itertools.chain(*contacts)):
   return True

这工作正常,但非常丑陋。非常重复的代码,很难read/understad发生了什么。

如您所见,有 3 行是我想要的,而我必须至少编写 30 行才能使这 3 行起作用。

在这张图片中,我展示了我正在寻找的东西。实体是灰色区域,邻居是红色区域。我想看看邻居有没有住满

获得这些邻居的正确方法是什么?

假设您将代码放入一个函数中:

 leftside = max(0, start -1)
 rightside = min(end + 1, len(t_field) - 1)

 if row >= 1:
     if any(t_field[row -1][leftside:rightside]): return True
 if row < len(t_field) - 1:
     if any(t_field[row + 1][leftside:rightside]): return True
 return False