CC-20 : Solve Towers of Hanoi problem with N disks.
Description:
The Towers of Hanoi is a puzzle that consists of three poles. There are disks, stacked from largest size (bottom) disk to smallest size (top most disk) on first pole. The goal is to move the entire stack to last pole by moving only one disk at a time, while never placing a larger disk on top of a smaller one. The middle pole can be used as a temporary or transit pole. Given an input num N, solve the Tower of Hanoi problem assuming n disks on the first pole.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| N=3 |
Move disk 1 from T1 to T3 Move disk 2 from T1 to T2 Move disk 1 from T3 to T2 Move disk 3 from T1 to T3 Move disk 1 from T2 to T1 Move disk 2 from T2 to T3 Move disk 1 from T1 to T3 |
Pseudocode:
sumDigits(N):
| • Input parameters are : numdisks, From, temp, to. These refer to of number of disks to be moved and are String references to first pole, temporary pole and last pole. |
| If numDisks==0:
return.
|
| Else :
Recursively call towersOfHanoi(numDisks-1, from, to, temp).Note the change in the order of the pole references in method call.
Print "Move disk "+numDisks+" from "+from+" to "+to.
Recursively call towersOfHanoi(numDisks-1, temp, from ,to). Note the change in the order of the pole references in method call.
|
Code:
public void towersOfHanoi(int numDisks, String from, String temp, String to){
if (numDisks==0) {return;}
towersOfHanoi(numDisks-1, from,to,temp);
System.out.println("Move disk "+numDisks+" from "+from+" to "+to);
towersOfHanoi(numDisks-1, temp,from,to);
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |