繁体   English   中英

最近邻算法

[英]Nearest neighbor algorithm

我有我的最近邻算法,我试图通过一个循环中的所有点 go 。 路径的长度计算为路径上相邻点之间的欧几里得距离之和,就像我在 function “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))

我修改了你的最后一段代码,假设你正在为输入中的每个点寻找最近的邻居。

circuit = set()
visited_islands = []
for current_vertex in range(n):
    min_distance = None
    best_v = None
    for v in range(n):
        if current_vertex == v:
            continue
        if ((min_distance is None) or
                (min_distance > dist(current_vertex, v))):
            min_distance = dist(current_vertex, v)
            best_v = v
    circuit.add((current_vertex, best_v))
    visited_islands.append(current_vertex+1)

print(*visited_islands)
print(circuit)

Output:

1 2 3 4

{(0, 1), (1, 0), (2, 1), (3, 0)}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM