/*Program to simulate Tower of Hanoi function*/
#include <stdio.h>
int main()
{
int stack1[10],top=-1,n;
char stack2[10],stack3[10],stack4[10];
char x='A',y='B',z='C',temp; //towers
//Tower of Hanoi function is similar to inorder traversal of a binary tree
printf("\nEnter number of plates : ");
scanf("%d",&n);
while(n>0)
{
top++;
stack1[top]=n;stack2[top]=x;stack3[top]=y;stack4[top]=z;//push()
n--;
temp=y;//traverse left(recursion tree)
y=z;
z=temp;
}
while(top!=-1)
{
n=stack1[top];x=stack2[top];y=stack3[top];z=stack4[top];//pop()
top--;
printf("\n%c->%c",x,y);//visit
//traverse right subtree
temp=z;
z=x;
x=temp;
n--;
while(n>0)//traverse left
{
top++;
stack1[top]=n;stack2[top]=x;stack3[top]=y;stack4[top]=z;//push()
n--;
temp=y;//traverse left(recursion tree)
y=z;
z=temp;
}
}
}
No comments:
Post a Comment