1.

Write a Java program for solving the Tower of Hanoi Problem.

Answer»

public CLASS InterviewBit{ //Recursive Method for SOLVING the Tower of hanoi. private static void TOH(CHAR source, char auxiliary, char destination, int numOfDisk){ if (numOfDisk > 0){ TOH(source, destination, auxiliary, numOfDisk-1); System.out.println("Move 1 disk from "+source+" to "+destination+" using "+auxiliary+"."); TOH(auxiliary, source, destination, numOfDisk-1); } } public static void main(String[] args) { TOH('A','B','C', 3); }}

In the above code we are first moving the n-1 disk from Tower A to Tower B, then moving that nth disk from Tower A to Tower C, and finally, the remaining n-1 disk from Tower B to Tower C. And we are doing this recursively for the n-1 disk.



Discussion

No Comment Found