tower_of_hanoi.cpp File Reference

Solve the Tower of Hanoi problem. More...

`#include <iostream>`
Include dependency graph for tower_of_hanoi.cpp:

## Classes

struct | tower

## Functions

void | show (const struct tower *const F, const struct tower *const T, const struct tower *const U)
void | mov (tower *From, tower *To)
void | TH (int n, tower *From, tower *Using, tower *To)
int | main ()

## Detailed Description

Solve the Tower of Hanoi problem.

## Function Documentation

## main()

int main | ( | void |  | ) |

Main function

{
struct tower F, U, T;
F.top = 0;
U.top = 0;
T.top = 0;
int no;
std::cout << "\nEnter number of discs : ";
std::cin >> no;
for (int i = no; i > 0; i--) {
F.values[F.top++] = i;
}
show(&F, &T, &U);
TH(no, &F, &U, &T);
return 0;
}
std::cin
std::cout
tower
Definition: tower_of_hanoi.cpp:11
tower::top
int top
top tower ID
Definition: tower_of_hanoi.cpp:15
show
void show(const struct tower *const F, const struct tower *const T, const struct tower *const U)
Definition: tower_of_hanoi.cpp:19
TH
void TH(int n, tower *From, tower *Using, tower *To)
Definition: tower_of_hanoi.cpp:52
Here is the call graph for this function:

## mov()

void mov | ( | tower * | From,
|  | tower * | To
| ) |  |

Move one disc from one tower to another

Parameters

  [in,out] | From | tower to move disk from
  [in,out] | To | tower to move disk to

{
--From->top;
To->values[To->top] = From->values[From->top];
++To->top;
}
tower::values
int values[10]
Values in the tower.
Definition: tower_of_hanoi.cpp:13

## show()

void show | ( | const struct tower *const | F,
|  | const struct tower *const | T,
|  | const struct tower *const | U
| ) |  |

Display the towers

{
std::cout << "\n\n\tF : ";
for (int i = 0; i < F->top; i++) {
std::cout << F->values[i] << "\t";
}
std::cout << "\n\tU : ";
for (int i = 0; i < U->top; i++) {
std::cout << U->values[i] << "\t";
}
std::cout << "\n\tT : ";
for (int i = 0; i < T->top; i++) {
std::cout << T->values[i] << "\t";
}
}

## TH()

void TH | ( | int | n,
|  | tower * | From,
|  | tower * | Using,
|  | tower * | To
| ) |  |

Recursive algorithm to solve the puzzle

Parameters

  [in] | n | starting number of disks
  [in,out] | From | tower to move disks from
  [in,out] | Using | temporary tower for the puzzle
  [in,out] | To | tower to move disk to

{
if (n == 1) {
mov(From, To);
show(From, To, Using);
} else {
TH(n - 1, From, To, Using);
mov(From, To);
show(From, To, Using);
TH(n - 1, Using, From, To);
}
}
mov
void mov(tower *From, tower *To)
Definition: tower_of_hanoi.cpp:39
Here is the call graph for this function: