4

我正在尝试找到一种在列表列表中查找给定节点的所有邻居的方法。数组如下所示:

0,2,4,1,6,0,0
2,0,0,0,5,0,0
4,0,0,0,5,5,0
1,0,0,0,1,1,0
6,5,0,1,0,5,5
0,0,5,1,5,0,0
0,0,0,0,5,0,0

到目前为止,我的代码是:

#!/usr/bin/python

#holds all source nodes
source = []

#read in and store the matrix
def create_matrix(file):
    with open('network.txt') as f:
        Alist = []
        for line in f:
            part = []
            for x in line.split(','):
                part.append(int(x))
            Alist.append(part)
    return Alist

def check_neighbours(Alist):
    i = iter(Alist)
    item = i.next()
    source.append(item)
    print source

file = ("F:/media/KINGSTON/Networking/network.txt")
Alist = create_matrix(file)
check_neighbours(Alist)

显然,这只输出矩阵的第一行,但我想要一些不同的东西。例如,我将从节点 [0,0] 开始,它是 0,然后找到 [0,1] 和 [1,0]。但如果我不在矩阵的边缘,我还需要查看 3x3 半径。我知道如何找到当前节点右侧的下一个邻居,但我真的不确定如何在节点旁边找到任何东西,包括对角节点。

4

1 回答 1

7

您需要一个 8 邻居算法,它实际上只是从列表列表中选择索引。

# i and j are the indices for the node whose neighbors you want to find
def find_neighbors(m, i, j, dist=1):
    return [row[max(0, j-dist):j+dist+1] for row in m[max(0, i-1):i+dist+1]]

然后可以通过以下方式调用:

m = create_matrix(file)
i = some_y_location
j = some_x_location
neighbors = find_neighbors(m, i, j)

没有列表压缩的实现:

def find_neighbors(m, i, j, dist=1):
    neighbors = []
    i_min = max(0, i-dist)
    i_max = i+dist+1
    j_low = max(0, j-dist)
    j_max = j+dist+1
    for row in m[i_min:i_max]:
        neighbors.append(row[j_min:j_max])
    return neighbors

您需要对 i/j_min 进行最大调用以避免负索引,但上限值太大由列表切片自动处理。

如果您希望将这些行列表作为单个元素列表,则需要添加:

neighbors = [elem for nlist in neighbors for elem in nlist]

这会使列表列表变平。

如果您想要邻居的指标(可能有更清洁的解决方案):

def find_neighbor_indices(m, i, j, dist=1):
    irange = range(max(0, i-dist), min(len(m), i+dist+1))
    if len(m) > 0:
        jrange = range(max(0, j-dist), min(len(m[0]), j+dist+1))
    else:
        jrange = []
    for icheck in irange:
        for jcheck in jrange:
            # Skip when i==icheck and j==jcheck
            if icheck != i or jcheck != j:
                neighbors.append((icheck, jcheck))
    return neighbors
于 2013-04-09T22:40:01.450 回答