#include #include "towers.h" /* ---------------------------------------------------------------------- */ /* Solve the problem for npieces disks */ solve_tower(Dllist *towers, int from, int to, int npieces) { int other; int i; /* Find the identity of the other tower */ for (i = 0; i < 3; i++) { if (from != i && to != i) other = i; } /* Move the top n-1 pieces to the other tower */ if (npieces > 1) { solve_tower(towers, from, other, npieces-1); } /* Move the remaining piece to the destination */ make_move(towers, from, to); /* Move the top n-1 pieces onto the destination */ if (npieces > 1) { solve_tower(towers, other, to, npieces-1); } } /* ---------------------------------------------------------------------- */ /* Main -- allocate, print, solve, print */ main(int argc, char **argv) { Dllist *towers; int npieces; if (argc != 2) { fprintf(stderr, "usage: tower_solution size\n"); exit(1); } npieces = atoi(argv[1]); if (npieces <= 0) exit(1); towers = new_towers(npieces); print_towers(towers); solve_tower(towers, 0, 1, npieces); print_towers(towers); }