#include using namespace std; const int NMAX = 15; int height[3]; //-------- #ifdef NOGRAPHICS void initGraphics(int n, int a) {} void updateGraphics(int a, int b) {} #else #include int disk[3][NMAX]; int nDisks; void drawTowers() { int nx = wio.xmax(); int ny = wio.ymax(); int colorStep = (wio.number_of_colors() - 2) / nDisks; int x[3] = { nx/6, nx/2, nx*5/6 }; int y0 = ny / 3; int diskHeight = nx / 4 / nDisks; int maxRadius = nx / 7; int radiusStep = maxRadius / nDisks; wio << white << FilledRectangle(0, 0, nx, ny); wio << black << FilledRectangle(0, 0, nx, y0); for (int a = 0; a < 3; a++) { wio << black << FilledRectangle(x[a]-5, y0-1, x[a]+5, ny * 2/3); for (int i = 0; i < height[a]; i++) { int d = disk[a][i]; int y = y0 + i * diskHeight; int r = maxRadius - d * radiusStep; wio << color(colorStep * d) << FilledRectangle(x[a]-r, y, x[a]+r, y+diskHeight-1); } } wio.flush(); wio.get_key(); } void initGraphics(int n, int a) { for (int i = 0; i < n; i++) disk[a][i] = i; // disk #0 is largest nDisks = n; drawTowers(); } void updateGraphics(int a, int b) { disk[b][height[b]-1] = disk[a][height[a]]; drawTowers(); } #endif //-------- void initialize(int n, int a) { height[0] = height[1] = height[2] = 0; height[a] = n; initGraphics(n, a); } void move(int n, int a, int b) // move n top disks from tower a to tower b { if (n == 1) { height[a]--; height[b]++; cout << "vom Turm " << a << " zum Turm " << b << "\n"; updateGraphics(a, b); } else { int c = 3-a-b; // the remaining tower move(n-1, a, c); // recursive call: put to temporary place move(1, a, b); // move a single disk from a to b move(n-1, c, b); // recursive call: get from temporary space } } int main(int argc, char** argv) { int n; if (argc > 1) n = atoi(argv[1]); else n = 5; initialize(n, 0); move(n, 0, 2); return 0; }