There’s 2d array, with points marked on it – just like in the first picture. What I have to do, is to find connection between all the points on that map (so you can travel from any point to all other points). Sum of length of all edges has to be possibly smallest.

Input:
(0, 0) (5, 5) (5, 1) (4, 4) (1, 5) (2, 4) (2, 1) // 1st,2nd,3rd city ...
Output:
1-7, 7-3, 7-6, 6-5, 6-4, 4-2
Treat your input set of points as a fully connected graph, with the distance between a pair of points as the edge weight. Then find the minimum spanning tree of the graph.
Kruskal’s algorithm is particularly easy:
There are various techniques you can use to make this very fast if speed is an issue.