1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
|
// Tower_of_Hanoi_Animated.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
#define MAX_LEVELS 10
// Declare three pole positions, or rather, stacks.
// Each stack is an object containing ring values.
// stacks[3] is an array three of these objects.
class mystack {
public:
int rings[MAX_LEVELS];
int tos;
void populate(int size);
void clear(int size);
void push(int n);
int pop(void);
} stacks[3];
void mystack::populate(int size) {
for (int i = 0; i < size; i++)
rings[i] = i + 1;
tos = -1;
}
void mystack::clear(int size) {
for (int i = 0; i < size; i++)
rings[i] = 0;
tos = size - 1;
}
void mystack::push(int n) {
rings[tos--] = n;
}
int mystack::pop(void) {
int n = rings[++tos];
rings[tos] = 0;
return n;
}
void move_stacks(int src, int dest, int other, int n);
void move_a_ring(int source, int dest);
void print_stacks(void);
void pr_chars(int ch, int n);
int stack_size = 7;
int _tmain() {
stacks[0].populate(stack_size);
stacks[1].clear(stack_size);
stacks[2].clear(stack_size);
print_stacks();
move_stacks(stack_size, 0, 2, 1);
return 0;
}
// Move stacks: solve problem recursively...
// move N stacks by assuming proble solved for N-1
// src = source stack, dest = destination stack.
//
void move_stacks(int n, int src, int dest, int other) {
if (n == 1)
move_a_ring(src, dest);
else {
move_stacks(n-1, src, other, dest);
move_a_ring(src, dest);
move_stacks(n-1, other, dest, src);
}
}
// Move a Ring: Pop off a ring from source (src) stack,
// place it on destionation stack, and print new state.
//
void move_a_ring(int source, int dest) {
int n = stacks[source].pop();
stacks[dest].push(n);
print_stacks();
}
// Print Stacks: For each physical level, print the
// ring for each of the three stacks.
//
void print_stacks(void) {
int n = 0;
for (int i = 0; i < stack_size; i++) {
for (int j = 0; j < 3; j++) {
n = stacks[j].rings[i];
pr_chars(' ', 12 - n);
pr_chars('*', 12 - n);
pr_chars(' ', 12 - n);
}
cout << endl;
}
system("PAUSE");
}
void pr_chars(int ch, int n) {
for (int i = 0; i < n; i++)
cout << (char) ch;
}
|