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,intermediatemove(n, 'A', 'C', 'B');}// function to find the moves in tower of hanoi problemstatic void move(int n, char source, char destination, char inter) {// base case if only one leftif (n == 1)System.out.println("Move from " + source + " to " + destination);// else call for n-1else {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 problemvoid move(int n,char source,char destination,char inter){//base case if only one leftif(n==1)cout<<"Move from "<<source<<" to "<<destination<<"\n";//else call for n-1else{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,intermediatemove(n,'A','C','B');return 0;}
No comments:
Post a Comment