-1

I am writing a travelling salesman program, which is to calculate distance between all the points and determine the shortest distance using the BRUTE Force method. This is not homework :)

My approach is to generate all the possible points arrangement first, using the std next_permutation function.

Using the std next_permutation function will generate the output orders:

(assume that there are 3 points)

123

132

213

231

312

321

(same with if there are 4 points)

1234

1243

...

4312

4321

However the program is slow due to repetitive, such as the distance of 123 is the same with 321 (although I did not run the calculations twice, I have saved each distance into a struct). Lets take back the example with 3 points AFTER I eliminate the repeating, the output will now become

123

132

213

saving at least half the work, more as the number of points increases. I have written out a few alternatives to eliminate the repetitive orders however have no idea how to express it out in a code (help).

I will post the few alternatives that I have figured out here, if requested.

If anyone could post your idea in the form of pseudocode, on how can I eliminate the repetitive orders. Thanks!

Lim Zheng Yue
  • 51
  • 3
  • 6
  • This is not a very good questions for StackOverflow (see the [FAQ] and [How to ask](http://stackoverflow.com/questions/how-to-ask)). – sashoalm Apr 03 '13 at 11:33

1 Answers1

1

Since this hasn't been closed, I'll make a quick suggestion.

You really should be looking at a modification of BFS. Where the marked set is replaced by simply checking if the adjacent vertex isn't already in the path, which can be made faster by also keeping a set containing all of the vertices in the path, instead of checking each vertex in the path one by one.

The idea is to have something like this:
1 - Start with the initial path [1]
12 - expand the path [1] to the path [1,2]
13 - expand the path [1] to the path [1,3]
123 - expand the path [1,2] to the path [1,2,3]
132 - expand the path [1,3] to the path [1,3,2]

I have only two solutions, while you have three. This is because the cycle, 213 is the same as the cycle, 132, as can be seen when it's written like so: 2-1-3-2-1.

Modifying Depth-First Search in the same manner would also work.

This is still only a slight improvement on brute force relatively speaking. Strictly speaking, the program is going to be slow because it's brute force, and will not be of much use beyond around 20 points, as noted in the wikipedia page.

Nuclearman
  • 5,029
  • 1
  • 19
  • 35