Towers Hanoi Algorithm

matrixlab 9,940 views 17 slides Oct 23, 2014
Slide 1
Slide 1 of 17
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17

About This Presentation

Understand and solve the famous puzzle called the Towers of Hanoi. Coded recursion can be used and a demonstration in Matlab is given. For more information, visit:
http://matrixlab-examples.com/tower-of-hanoi-algorithm.html


Slide Content

The Towers of Hanoi
Algorithm
In Matlab

Towers of Hanoi Algorithm
•In this demonstration we’ll use 4 disks. The
objective of the puzzle is to move all of the
disks from tower A to tower C.

Towers of Hanoi Algorithm
Easy Rules:
•Only one disk can be moved at a time and it can
only be the top disk of any tower.
•Disks cannot be stacked on top of smaller disks.

Towers of Hanoi Algorithm
We’re going to solve the puzzle by using
recursion.
Recursion is a computer programming technique
that involves the use of a procedure that calls
itself one or several times until a specified
condition is met.

Towers of Hanoi Algorithm
If we want to move disk 4 from A to C, after
several moves and at some point, we MUST be
in this situation:

Towers of Hanoi Algorithm
And now, we can accomplish our first goal: move
the largest disk to its final destination.

Towers of Hanoi Algorithm
But now, if we ignore tower C, we are just like we
were at the beginning, but with just 3 disks left
(instead of 4)! We’ve simplified the puzzle!

Towers of Hanoi Algorithm
If we want to move disk 3 from B to C, after
several moves and at some point, we MUST be
in this situation:

Towers of Hanoi Algorithm
And now, we can accomplish our second goal:
move the second largest disk to its final
destination.

Towers of Hanoi Algorithm
Now, the position is trivial to finish… but we still
can repeat the ideas above.

Towers of Hanoi Algorithm
Let’s code that with recursion. We’ll call our
function m (for move) and we’ll have four input
parameters:
m(n, init, temp, fin)
where
n is the number of disks to move
init is the initial tower
temp is the temporary peg
fin is the final tower

Towers of Hanoi Algorithm
We have three situations to consider:
1.- m(n-1, init, fin, temp)
we’ll move n-1 disks from A to B, with C as
temporary peg.

Towers of Hanoi Algorithm
2.- m(1, init, temp, fin)
we’ll move 1 disk (our partial goal) from
A to C, with B as temporary peg.

Towers of Hanoi Algorithm
3.- m(n-1, temp, init, fin)
we’ll move n-1 disks from B to C, with A as
temporary peg.

Towers of Hanoi Algorithm
In Matlab, our function would become:

Towers of Hanoi Algorithm
We can call it like this:
To get this result:

Towers of Hanoi Algorithm

For more examples and details, visit:
matrixlab-examples.com/tower-of-hanoi-algorithm.html