TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
tower_of_hanoi.cpp File Reference

Solve the Tower of Hanoi problem. More...

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

Go to the source code of this file.

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.

Definition in file tower_of_hanoi.cpp.

Function Documentation

◆ main()

int main ( void )

Main function

Definition at line 65 of file tower_of_hanoi.cpp.

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}
int top
top tower ID
void TH(int n, tower *From, tower *Using, tower *To)

◆ 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

Definition at line 39 of file tower_of_hanoi.cpp.

39 {
40 --From->top;
41 To->values[To->top] = From->values[From->top];
42 ++To->top;
43}
int values[10]
Values in the tower.

◆ show()

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

Display the towers

Definition at line 19 of file tower_of_hanoi.cpp.

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

Definition at line 52 of file tower_of_hanoi.cpp.

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}
void mov(tower *From, tower *To)