Posts Tower Of Hanoi (geeksforgeeks - SDE Sheet)
Post
Cancel

Tower Of Hanoi (geeksforgeeks - SDE Sheet)

PROBLEM DESCRIPTION

The tower of Hanoi is a famous puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod. You are given the number of discs n. Initially, these discs are in the rod 1. You need to print all the steps of discs movement so that all the discs reach the 3rd rod. Also, you need to find the total moves.

You only need to complete the function toh() that takes following parameters: n (number of discs), from (The rod number from which we move the disc), to (The rod number to which we move the disc), aux (The rod that is used as an auxiliary rod) and prints the required moves inside function body (See the example for the format of the output) as well as return the count of total moves made.

Note: The discs are arranged such that the top disc is numbered 1 and the bottom-most disc is numbered n. Also, all the discs have different sizes and a bigger disc cannot be put on the top of a smaller disc. Refer the provided link to get a better clarity about the puzzle.

geeksforgeeks

SOLUTION

Good Explanation on YouTube by Abdul Bari

MAIN STEPS

| Rod A (from) | Rod B (using) | Rod C (to) | | ———— | ————- | ———- |

  • Move (n-1) discs from A to B using C
  • Move a disc from A to C
  • Move (n-1) discs from B to C using A
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Hanoi {

    public long toh(int n, int from, int to, int aux) {

        if(n == 0)
            return 0;

        int moves = 0;

        moves += toh(n-1, from, aux, to);

        System.out.println("move disk " + n + " from rod " + from + " to rod " + to);

        moves++;

        moves += toh(n-1, aux, to, from);

        return moves;

    }
}
This post is licensed under CC BY 4.0 by the author.