home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!mcsun!sun4nl!and!jos
- From: jos@and.nl (Jos Horsmeier)
- Newsgroups: comp.lang.c
- Subject: Re: travelling salesman
- Message-ID: <4219@dozo.and.nl>
- Date: 14 Dec 92 14:48:29 GMT
- References: <FARID.92Dec11140244@gradient.cis.upenn.edu>
- Organization: AND Software BV Rotterdam
- Lines: 97
-
- In article <FARID.92Dec11140244@gradient.cis.upenn.edu> farid@gradient.cis.upenn.edu (Hany Farid) writes:
- |
- |I am looking for code that enumerates the (N-1)!/2 possible paths of
- |the travelling salesman for a map with N cities. Any help would be
- |appreciated.
-
- Note that only the first (N-1)! of all N! permutations need to be generated
- (since it doesn't matter which city is the start/end point) Also not that,
- when the cities are numbered 0 ... N-1, when the city _next_ to the starting
- point has a lower rank than the last city of the tour, this particular tour
- must occur somewhere earlier in the list of permutations (but backwards.)
-
- Maybe an example clarifies things a bit: Consider N= 4:
-
- 1234, 1243, 1324, 1342 (not valid: 2 < 3), 1423 (not valid: 3 < 4),
- 1432 (not valid: 2 < 4)
-
- So, 1234, 1243 and 1324 are the three possible tours for N= 4.
-
- Also note that we can stop generating permutations when the city next
- to the starting point has the highest rank number.
-
- The following program does the job for you:
-
- -----8<-----snip----------snip----------snip----------snip----------snip-----
- #include <stdio.h>
-
- #define N 6 /* or any number you want */
-
- void print_perm(a)
- int *a;
- {
- int i;
-
- for (i= 0; i < N; i++)
- printf("%d ", a[i]);
- printf("\n");
-
- }
-
- int main(void) {
-
- int i, tmp, a[N], b[N];
-
- /*
- * Set up first permutation
- */
- for (i = 0; i < N; i++)
- a[i] = b[i] = i;
-
- print_perm(a);
-
- /*
- * Keep on generating permutations
- */
- for (i = 0; i < N; i++) {
-
- if (b[i] < i) {
- tmp = a[i];
- a[i] = a[b[i]];
- a[b[i]] = tmp;
- }
-
- if (--b[i] >= 0) {
-
- tmp = a[i];
- a[i] = a[b[i]];
- a[b[i]] = tmp;
-
- /*
- * Test for the same route backwards
- */
- if (a[N-2] > a[0])
- print_perm(a);
- /*
- * Done first (N-1)!/2 ?
- */
- else if (!a[N-2])
- break;
-
- /*
- * Reiterate again
- */
- i= -1;
- continue;
-
- }
- b[i] = i;
- }
- }
- -----8<-----snip----------snip----------snip----------snip----------snip-----
-
- I hope this helps a bit,
-
- kind regards,
-
- Jos aka jos@and.nl
-