0

I know there have been many questions similar to this one, and I've reviewed them for the past hour, however I couldn't figure out how to solve my problem using the answers provided.

My task is as follows:

Write a program that prompts the user for a list of cities, where each city has a name and x and y coordinates. After all cities have been entered, the program should use a recursive algorithm to print the length of all possible routes that start at the first city entered, end at the last city entered, and visit every city in the list. For each route, the program should print the name of each city visited, followed by length of the route.

I broke down the problem and I can figure out out most of the code. What got me stuck was finding all possible combinations between the 1st and last cities. How the hell do I manage that? I'm trying to solve it with a simple array of 5 integers and for the life of me I can't figure out how to print all combinations.

Could you kindly assist me in overcoming this hideous problem?

Thank you.

Oz Pere
  • 111
  • 1
  • 7
  • Please post a short version of your code ([mcve] ). Best is to include coded test data to avoid user input. – c0der May 28 '17 at 03:43

3 Answers3

0

Rather than using an Array I would suggest you use a graph.

You can read more about the Travelling Salesman Problem here TSP or Brute-force for TSP

J.Kirk.
  • 943
  • 3
  • 12
  • 32
0

Are you forced to use recursive algorithm?

If no, here is my suggestion:

Suppose entered cities are A, C1, ..., Cn, B which A and B are first and last cities. First and last cities could not be changed, so you should compute all combination of n city. To compute all combinations, you can count from 0 to 2^n-1. For each value of counter you have a path form A to B. Each bit of each counter value could be related to one city (Ci). Now for each value of counter you can print a path form A to B (with some Ci):

  • If related bit of a city in counter value is 0 so related city is not a viewed city in the path
  • If related bit of a city in counter value is 1 so related city is a viewed city in the path.
hadi.mansouri
  • 828
  • 11
  • 25
0

It is a well-known graph approach. If you have knowledge about graphs, just taking a glance at DFS (recursively) most likely meets your expectation.