0

I am trying to solve the travelling salesman problem using Brute Force procedure by checking all possible permutations. I have done it in c++.

The main problem is this: the code works well for small input size. But when I am giving a file containing 16 Cartesian coordinates as input and run the program, the console hangs. It doesn't show anything. Seems like it will run forever. What's the main reason of this? I am using Code Blocks compiler.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • 10
    I don't know about you, but without looking at the rest of the question, the words, "traveling salesman", "brute-force", and "takes forever" makes it sound a bit too obvious. – Mysticial Sep 08 '16 at 20:45
  • https://en.wikipedia.org/wiki/Travelling_salesman_problem – OldProgrammer Sep 08 '16 at 20:48
  • Scatter some `printf` calls around to get a better idea off what's going on. Also, traveling salesman gets intractable pretty fast when using brute force. Slide 24 in [this PDF](https://www.math.ku.edu/~jmartin/courses/math105-F11/Lectures/chapter6-part3.pdf) shows how bad it is. – Ouroborus Sep 08 '16 at 20:48
  • 2
    The time complexity being O(n!), for your 16 entries it should be approx. 871782912000 times slower than for 4 entries (an so on). – Fabio Ceconello Sep 08 '16 at 20:54

1 Answers1

9

A brute-force algorithm for the traveling salesman problem has a complexity of approximately O(N!).

That means, for example, that 10 items have approximately 3,628,800 combinations for you to check. Just for the sake of discussion, let's say your computer can complete that in half a second.

In this case, you're trying to solve with 16 points. That's less than twice as big, so it doesn't seem like it should take a whole lot longer, right? In fact, 16! is 20,922,789,888,000. If the job took 0.5 second for 10 items, it should take about 5,765,760 * .5 seconds, which works out to about 33.4 days--i.e., running for 24 hours a day for more than a month.

Of course, the half a second time is just a guess--if it was only a tenth of a second, then we'd expect the 16-item version to take only about a week. On the other hand, if it was really closer to a whole second, then the 16-item task should take a couple months or so.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111