NxN数组检查邻居单元格

时间:2015-06-24 21:57:19

标签: python arrays nearest-neighbor

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

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

实体是一个1的序列,它有一个(行,开始),(行,结束),我想检查上面的行,下面的行,但是在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时会抛出和IndexError

开始/结束也一样,如果开始为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

这很好用,但它完全是丑陋的。非常重复的代码,很难阅读/了解正在发生的事情。

正如你所看到的,我想要的是3行,至少有30行是我必须写的,以使这3行有效。

Grid

在这张图片中,我展示了我在寻找什么。实体是灰色区域,邻居是红色区域。我想检查邻居是否被填满。

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

1 个答案:

答案 0 :(得分:1)

假设您将代码放在函数中:

 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