我使用一组LatLon点的scipy.spatial
Python库创建了一个Voronoi图,以找到每个点的邻居。然后,我发现Delaunay三角剖分会更有用,现在我可以使用这个算法轻松找到每个点的“第一层”和“第二层”邻居:
def findNeighbors(delaunay):
"Returns a adjacency list of the graph"
neighbors = defaultdict(set)
for simplex in delaunay.simplices:
for vertice in simplex:
other = set(simplex)
other.remove(vertice)
neighbors[vertice] = neighbors[vertice].union(other)
return neighbors
def neighborCount(graph, start, target):
if target in graph[start]:
return 'First Tier Neighbor'
elif graph[start] & graph[target]:
return 'Second Tier Neighbor'
但问题是我需要找到“第六层邻居”,而且我无法找到一种方法来做到这一点而不会遍历所有的邻接列表。以下是我想要找到的“第三层邻居”的示例。
有更聪明的方法吗?
答案 0 :(得分:0)
我发现广度优先搜索或深度优先搜索算法可以做到这一点,但它们也返回路径,我不需要这个,因此,我创建了一个只返回路径长度的函数,让它变得更快。
def getNeighbor(neighbors, graph):
out = set()
for neighbor in neighbors:
out = out.union(graph[neighbor])
return out
def tier_count(graph, start, target):
if target in graph[start]:
return "1 tier"
else:
visited = set()
queue = getNeighbor(graph[start], graph)
count = 2
while queue:
if target in queue:
return str(count) + " Tier'
else:
count += 1
visited = visited.union(queue)
queue = getNeighbor(queue, graph) - visited
return "No tiers between these cells"