Algorithms_in_C++  1.0.0
Set of algorithms implemented in C++.
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

65  {
66  struct tower F, U, T;
67 
68  F.top = 0;
69  U.top = 0;
70  T.top = 0;
71 
72  int no;
73 
74  std::cout << "\nEnter number of discs : ";
75  std::cin >> no;
76 
77  for (int i = no; i > 0; i--) {
78  F.values[F.top++] = i;
79  }
80 
81  show(&F, &T, &U);
82  TH(no, &F, &U, &T);
83 
84  return 0;
85 }
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]Fromtower to move disk from
[in,out]Totower to move disk to
39  {
40  --From->top;
41  To->values[To->top] = From->values[From->top];
42  ++To->top;
43 }

◆ show()

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

Display the towers

20  {
21  std::cout << "\n\n\tF : ";
22  for (int i = 0; i < F->top; i++) {
23  std::cout << F->values[i] << "\t";
24  }
25  std::cout << "\n\tU : ";
26  for (int i = 0; i < U->top; i++) {
27  std::cout << U->values[i] << "\t";
28  }
29  std::cout << "\n\tT : ";
30  for (int i = 0; i < T->top; i++) {
31  std::cout << T->values[i] << "\t";
32  }
33 }

◆ TH()

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

Recursive algorithm to solve the puzzle

Parameters
[in]nstarting number of disks
[in,out]Fromtower to move disks from
[in,out]Usingtemporary tower for the puzzle
[in,out]Totower to move disk to
52  {
53  if (n == 1) {
54  mov(From, To);
55  show(From, To, Using);
56  } else {
57  TH(n - 1, From, To, Using);
58  mov(From, To);
59  show(From, To, Using);
60  TH(n - 1, Using, From, To);
61  }
62 }
Here is the call graph for this function:
mov
void mov(tower *From, tower *To)
Definition: tower_of_hanoi.cpp:39
std::cout
tower
Definition: tower_of_hanoi.cpp:11
show
void show(const struct tower *const F, const struct tower *const T, const struct tower *const U)
Definition: tower_of_hanoi.cpp:19
tower::values
int values[10]
Values in the tower.
Definition: tower_of_hanoi.cpp:13
tower::top
int top
top tower ID
Definition: tower_of_hanoi.cpp:15
TH
void TH(int n, tower *From, tower *Using, tower *To)
Definition: tower_of_hanoi.cpp:52
std::cin