Showing posts with label Tower of Hanoi. Show all posts
Showing posts with label Tower of Hanoi. Show all posts

Wednesday, June 29, 2022

Tower of Hanoi

Tower of Hanoi

Problem Statement
From wiki-
The Tower of Hanoi is a mathematical puzzle where we have 3 rods and N disks. The puzzle starts with all the disks in ascending order of size on the first row. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:

1. Only one disk can be moved at a time.
2. Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack or on an empty rod.
3. No larger disk may be placed on top of a smaller disk.
-----x--x--x------





 import java.io.*; // for handling input/output

import java.util.*; // contains Collections framework

// don't change the name of this class
// you can add inner classes if needed
class Main {
    

static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) 
    { 
        if (n == 1
        { 
            System.out.println("1:" +  from_rod + "->" + to_rod); 
            return
        } 
        towerOfHanoi(n-1, from_rod, aux_rod, to_rod); 
        System.out.println(n + ":" +  from_rod + "->" + to_rod); 
        towerOfHanoi(n-1, aux_rod, to_rod, from_rod); 
    } 
      
    //  Driver method 
    public static void main(String args[]) 
    { Scanner sc=new Scanner(System.in);

        int n = sc.nextInt();
        towerOfHanoi(n, 'A''C''B');  // A, B and C are names of rods 
    } 
}

ads vert

Basic HTML Tables - Layout, HTML Tables, Attributes, Aside, Footer, Tr tag, Td tag, Th tag, Tbody

  Basic HTML Tables - Layout, HTML Tables, Attributes, Aside, Footer, Tr tag, Td tag, Th tag, Tbody < table >      < thead >    ...