最近邻居算法

我有最近邻居的算法,并且试图在一个循环中遍历所有点。路径的长度计算为路径上相邻点之间的欧几里得距离的总和,就像我在函数“ dist”中所做的一样。问题是由于某种原因它不能显示最后一点。

Input style:
n      #number of points
x1, y2 #coordinates of the point
x2, y2
...

example:
4
0 0
1 0
1 1
0 1
it gives me output >> 1 2 3 
the desired output should be >> 1 2 3 4
from math import sqrt

n = int(input())
points = []

for i in range(0, n):
    x, y = list(map(float, input().split()))
    points.append([x,y])


def dist(ip1, ip2):
    global points
    p1 = points[ip1]
    p2 = points[ip2]
    return sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)


circuit = set()
start_vertex = 0
dark_side = set(range(n)) - {start_vertex}

visited_islands = []
current_vertex = start_vertex
while len(dark_side) > 0:
    min_distance = None
    best_v = None
    for v in dark_side:
        if ((min_distance is None) or
                (min_distance > dist(current_vertex, v))):
            min_distance = dist(current_vertex, v)
            best_v = v

    visited_islands.append(current_vertex+1)
    circuit.add((current_vertex, best_v))
    dark_side.remove(best_v)
    current_vertex = best_v
# visited_islands.append(visited_islands[0]) #going to the start when done
print(*visited_islands)
# print(len(visited_islands))
评论