| 1 |
#include <stdio.h> |
| 2 |
|
| 3 |
#define stackrange 3 |
| 4 |
#define maxcells 18 |
| 5 |
#define false 0 |
| 6 |
#define true 1 |
| 7 |
|
| 8 |
int stack[stackrange + 1]; |
| 9 |
int freelist, movesdone; |
| 10 |
struct element |
| 11 |
{ |
| 12 |
int discsize; |
| 13 |
int next; |
| 14 |
}; |
| 15 |
|
| 16 |
struct element cellspace[maxcells + 1]; |
| 17 |
|
| 18 |
static inline void |
| 19 |
Error (char *emsg) |
| 20 |
{ |
| 21 |
printf (" Error in Towers: %s\n", emsg); |
| 22 |
} |
| 23 |
|
| 24 |
static inline void |
| 25 |
Makenull (int s) |
| 26 |
{ |
| 27 |
stack[s] = 0; |
| 28 |
} |
| 29 |
|
| 30 |
static inline int |
| 31 |
Getelement () |
| 32 |
{ |
| 33 |
int temp = 0; |
| 34 |
if (freelist > 0) |
| 35 |
{ |
| 36 |
temp = freelist; |
| 37 |
freelist = cellspace[freelist].next; |
| 38 |
} |
| 39 |
else |
| 40 |
Error ("out of space "); |
| 41 |
return (temp); |
| 42 |
} |
| 43 |
|
| 44 |
static inline void |
| 45 |
Push (int i, int s) |
| 46 |
{ |
| 47 |
int errorfound, localel; |
| 48 |
errorfound = false; |
| 49 |
if (stack[s] > 0) |
| 50 |
if (cellspace[stack[s]].discsize <= i) |
| 51 |
{ |
| 52 |
errorfound = true; |
| 53 |
Error ("disc size error"); |
| 54 |
}; |
| 55 |
if (!errorfound) |
| 56 |
{ |
| 57 |
localel = Getelement (); |
| 58 |
cellspace[localel].next = stack[s]; |
| 59 |
stack[s] = localel; |
| 60 |
cellspace[localel].discsize = i; |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
static inline void |
| 65 |
Init (int s, int n) |
| 66 |
{ |
| 67 |
int discctr; |
| 68 |
Makenull (s); |
| 69 |
for (discctr = n; discctr >= 1; discctr--) |
| 70 |
Push (discctr, s); |
| 71 |
} |
| 72 |
|
| 73 |
static inline int |
| 74 |
Pop (int s) |
| 75 |
{ |
| 76 |
int temp, temp1; |
| 77 |
if (stack[s] > 0) |
| 78 |
{ |
| 79 |
temp1 = cellspace[stack[s]].discsize; |
| 80 |
temp = cellspace[stack[s]].next; |
| 81 |
cellspace[stack[s]].next = freelist; |
| 82 |
freelist = stack[s]; |
| 83 |
stack[s] = temp; |
| 84 |
return (temp1); |
| 85 |
} |
| 86 |
else |
| 87 |
Error ("nothing to pop "); |
| 88 |
return -1; |
| 89 |
} |
| 90 |
|
| 91 |
static inline void |
| 92 |
Move (int s1, int s2) |
| 93 |
{ |
| 94 |
Push (Pop (s1), s2); |
| 95 |
movesdone = movesdone + 1; |
| 96 |
} |
| 97 |
|
| 98 |
static void |
| 99 |
tower (int i, int j, int k) |
| 100 |
{ |
| 101 |
int other; |
| 102 |
if (k == 1) |
| 103 |
Move (i, j); |
| 104 |
else |
| 105 |
{ |
| 106 |
other = 6 - i - j; |
| 107 |
tower (i, other, k - 1); |
| 108 |
Move (i, j); |
| 109 |
tower (other, j, k - 1); |
| 110 |
} |
| 111 |
} |
| 112 |
|
| 113 |
int |
| 114 |
main () |
| 115 |
{ |
| 116 |
int i; |
| 117 |
for (i = 1; i <= maxcells; i++) |
| 118 |
cellspace[i].next = i - 1; |
| 119 |
freelist = maxcells; |
| 120 |
Init (1, 14); |
| 121 |
Makenull (2); |
| 122 |
Makenull (3); |
| 123 |
movesdone = 0; |
| 124 |
tower (1, 2, 14); |
| 125 |
if (movesdone != 16383) |
| 126 |
printf (" Error in Towers.\n"); |
| 127 |
return 0; |
| 128 |
} |