Tower of Hanoi

Program for a tower of Hanoi.

Example:

Input:  2
Output: Move from A to B
Move from A to C
Move from B to C

Approach

Java


public class TowerHanoi {
    public static void main(String[] args) {
        int n = 2;

        // call for n,source,destination,intermediate
        move(n, 'A''C''B');
    }

    // function to find the moves in tower of hanoi problem
    static void move(int nchar sourcechar destinationchar inter) {
        // base case if only one left
        if (n == 1)
            System.out.println("Move from " + source + " to " + destination);
        // else call for n-1
        else {
            move(n - 1, source, inter, destination);
            move(1, source, destination, inter);
            move(n - 1, inter, destination, source);
        }

    }
}

C++

#include <bits/stdc++.h>
using namespace std;

//function to find the moves in tower of hanoi problem
void move(int n,char source,char destination,char inter)
{

    //base case if only one left
    if(n==1)
      cout<<"Move from "<<source<<" to "<<destination<<"\n";

    //else call for n-1
    else
    {
        move(n-1,source,inter,destination);
        move(1,source,destination,inter);
        move(n-1,inter,destination,source);
    }
    
}
int main()
{
    int n=2;

    //call for n,source,destination,intermediate
    move(n,'A','C','B');
    return 0;
}


No comments:

Post a Comment