说,我给定了一组点(在笛卡尔平面中),我想找到到达一个公共点的最小步长,其中步长=所有点所采取的所有步长之和。一次只能将我们向上,向左,向右或向下四个方向移动。
我的想法: 我尝试一次在每个点上执行BFS,并检查所有点是否都访问了一个公共点。如果他们有的话,我只是总结到达共同点的距离。 这是我的代码:
from collections import deque
class Point:
def __init__(self, x, y, distance):
self.x = x
self.y = y
self.distance = distance
def __hash__(self):
return hash(self.x) + hash(self.y)
def __eq__(self, value):
return isinstance(value, Point) and self.x == value.x and self.y == value.y
def __repr__(self):
return "({}, {}, {})".format(self.x, self.y, self.distance)
def find_min_dist(positions):
qs = [deque() for _ in range(len(positions))]
visited_list = [set() for _ in range(len(positions))]
for i, pos in enumerate(positions):
point = Point(pos[0], pos[1], 0)
qs[i].append(point)
visited_list[i].add(point)
def hasCommon(visited_list):
if len(visited_list) == 0:
return set()
s = visited_list[0]
i = 1
while i < len(visited_list):
s = s.intersection(visited_list[i])
i += 1
return s
while len(hasCommon(visited_list)) == 0:
for i, q in enumerate(qs):
point = q.popleft()
for move in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
x = point.x + move[0]
y = point.y + move[1]
new_point = Point(x, y, point.distance + 1)
if new_point not in visited_list[i]:
q.append(new_point)
visited_list[i].add(new_point)
s = hasCommon(visited_list).pop()
dist = 0
for v in visited_list:
for e in v:
if e == s:
dist += e.distance
return dist
if __name__ == '__main__':
points = [(0, 1), (1, 0), (0, -2), (-1, 0)]
print(find_min_dist(points))
这对于给定的点集= [(0,1),(1,0),(0,-2),(-1,0)]有效。但是,如果我的点是[(0,1),(1,0),(0,-3),(-1,0)],它给我8,这是错误的答案。正确答案是5。有人可以帮助我解决我的问题吗?
谢谢!