DEV Community

Swapnil Gupta
Swapnil Gupta

Posted on

2 2

Tower of Hanoi: Recursion Problem

problem: three poles having disk in it , A-B-C, you have to move all disk from A to C using B as helper.
Rules:

  • arranged in manner that larger at bottom and smaller at top, so smaller should not be lower to larger one.
  • print all steps to move all the disk Image description

we can also write :
move n-1 discs from A to B using C
move a disc from A to C
move n-1 Discs from B to C using A

void TowerOfHanoi(int n, Int A, int B, Int C  ){
if(n>0){
   TowerOfHanoi(n-1, A, C, B);
printf("Moving disc from %d to %d", A, C);
TowerOfHanoi(n-1,B,A,C);
}
}



Enter fullscreen mode Exit fullscreen mode

for (n-1) or 1 disk it is easy to move,

Image description

solution Reference: Tower of Hanoi Problem - Made Easy

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay