Last active
March 2, 2016 06:16
-
-
Save SohanChy/cfebe75565bd56dc01a3 to your computer and use it in GitHub Desktop.
A recursive solution to the towers of hanoi problem in C++ using built in stack
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <bits/stdc++.h> | |
using namespace std; | |
void pegPrint(stack<int> peg,char x) | |
{ | |
cout<<"********** "<<x<<" ************"<<endl; | |
for(; peg.empty() != true; peg.pop()) | |
{ | |
cout<<"- "; | |
for(int i=0; i<peg.top(); i++) | |
{ | |
cout<<"O"; | |
} | |
cout<<" -"<<endl; | |
} | |
cout<<"***************************"<<endl<<endl; | |
} | |
void moveStack(stack<int> &src, stack<int> &dest) | |
{ | |
dest.push(src.top()); | |
src.pop(); | |
} | |
void hanoi(int n, stack<int> &A,stack<int> &B, stack<int> &C) | |
{ | |
//uncomment these to see each step | |
// cout<<n<<endl; | |
// pegPrint(A,'A'); | |
// pegPrint(B,'B'); | |
// pegPrint(C,'C'); | |
if(n==1) | |
{ | |
moveStack(A,C); | |
return; | |
} | |
hanoi(n-1,A,C,B); | |
moveStack(A,C); | |
hanoi(n-1,B,A,C); | |
return; | |
} | |
int main() | |
{ | |
stack<int> A,B,C; | |
int n = 9; | |
for(int i=n; i>0; i--) | |
{ | |
A.push(i); | |
} | |
pegPrint(A,'A'); | |
pegPrint(B,'B'); | |
pegPrint(C,'C'); | |
hanoi(n,A,B,C); | |
pegPrint(A,'A'); | |
pegPrint(B,'B'); | |
pegPrint(C,'C'); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a very helpful tree diagram for understanding the underlying logic of the recursive algorithm.

This shows the approach for n = 3