U
U
ukoHka2017-02-25 15:58:03
Pascal
ukoHka, 2017-02-25 15:58:03

How to get around all the vertices of the graph in the shortest way?

Given n points on a plane with two non-negative coordinates. The player needs to bypass them all. What is the minimum distance you need to go to go around all the points if the player always starts from the point (0,0)?
I know that this is a graph problem, I know that there are a lot of algorithms, Dijkstra's algorithm can help solve it, maybe it's a Hamiltonian graph, etc. But I couldn’t figure it all out, so it’s the implementation that interests me.
So far, there is only: counted points in an array, built an adjacency matrix, which is symmetrical with respect to the main diagonal, and then nothing. In the adjacency matrix, a[i,j] contains the distance between the i-th and j-th points, including the starting point.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
longclaps, 2017-02-25
@ukoHka

This is the traveling salesman problem , solved by enumeration.
Here's a solution for you in python, in pascal you somehow yourself)

from math import hypot

# тестовые варианты наборов точек
points = [(3, 4), (7, 7)]
points = [(3, 0), (3, 4), (6, 4)]
points = [(1, 0), (1, 8), (0, 8)]

INF = 1e20  # будем считать, что это - бесконечность
def f(startx, starty):
    res = INF
    for i, (x, y) in enumerate(points):
        if x >= 0:
            points[i] = (-1, -1)  # подменяю использованую точку на фиктивную
            t = hypot(startx - x, starty - y) + f(x, y)  # вот рекурсия, как обещал
            if res > t:
                res = t
            points[i] = (x, y)  # восстанавливаю точку
    if res == INF:  # не нашлось ни одной неиспользованой точки
        res = 0
    return res

print(f(0, 0))  # стартую из начала координат

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question