// by rue_mohr
volatile int beatCost;
int GetDestinations ( int sourceNode, int destnode, int cost, int tab );
int otherEnd (int knownEnd, int track);
int trackCost(int track);
void indent( int amount);
typedef struct direction_s {
int node;
int LeftTrack;
int RightTrack;
} direction;
typedef struct distance_s {
int track;
int distance;
} distance;
typedef struct fork_s {
int node;
int track;
} fork;
#define numDirections 18
direction directions[] = {
/* node, left track, right track */
{1, 1, 2},
{1, 2, 6},
{1, 6, 1},
{2, 6, 7},
{2, 7, 5},
{2, 5, 6},
{3, 5, 8},
{3, 8, 4},
{3, 4, 5},
{4, 1, 9},
{4, 9, 8},
{4, 8, 1},
{5, 2, 3},
{5, 3, 7},
{5, 7, 2},
{6, 4, 3},
{6, 3, 9},
{6, 9, 4}
};
#define numTracks 9
distance distances[] = {
/* track, distance */
{1, 2},
{2, 2},
{3, 3},
{4, 4},
{5, 7},
{6, 2},
{7, 5},
{8, 1},
{9, 5}
};
#define numForks 18
fork forks[] = {
/* node, track */
{1, 1},
{1, 2},
{1, 6},
{2, 5},
{2, 6},
{2, 7},
{3, 4},
{3, 5},
{3, 8},
{4, 1},
{4, 8},
{4, 9},
{5, 2},
{5, 3},
{5, 7},
{6, 3},
{6, 4},
{6, 9}
};
int main(void) {
int src; // source node
int dest; // destinaion source
int stack[23];
int i;
src = 3;
dest = 5;
for (i = 0; i <22; i++) stack[i] = 0;
beatCost = 0;
GetDestinations ( src, dest, 0, 0 );
printf("\n");
}
int GetDestinations ( int sourceNode, int destNode, int cost, int tab ) {
int i;
int newEnd;
int newCost;
indent( tab);
printf("->\n");
for (i = 0; i < numForks; i++) {
if (sourceNode == forks[i].node) {
newEnd = otherEnd(sourceNode, forks[i].track);
newCost = trackCost(forks[i].track);
indent( tab);
printf("N%d T%d N%d %d+%d=%d\n", sourceNode, forks[i].track, newEnd, cost, newCost, cost+newCost);
if (
(newEnd != destNode) &&
((cost+newCost < beatCost) || (beatCost == 0))
)
{
GetDestinations(newEnd, destNode,cost+newCost, tab+1);
if ((cost > beatCost) || (beatCost != 0)){ // still try to persue?
continue;
}
} else {
if ((cost+newCost < beatCost) || (beatCost == 0)) {
beatCost = cost+newCost;
indent( tab);
printf("--->HIT! N%d via T%d new cost = %d <------\n", newEnd, forks[i].track, beatCost);
}
}
}
}
indent( tab);
printf( "<-\n");
}
int otherEnd (int knownEnd, int track) {
int i;
for (i = 0; i < numForks; i++) {
if ((knownEnd != forks[i].node) && (track == forks[i].track)) {
return forks[i].node;
}
}
}
int trackCost(int track) {
int i;
for (i = 0; i < numTracks; i++) {
if (track == distances[i].track) {
return distances[i].distance;
}
}
}
void indent( int amount) {
int i;
for( i = 0; i < amount ; i++) {
printf(" ");
}
}