Computer Scientists are Pretty Pessimistic

Wednesday, 15 June 2016

Stack Algorithm for Tower of Hanoi Problem

Algorithm ::


S empty stack
S <= ( n, 1, 2, 3 )
While S empty do
      (n, i, j, k) <= S
       if
           n=1 then move the top disk from pole i to k
       else
           S <= (n-1, i, j , k)
           S <= (1, i, j , k)
           S <= (n-1, i, k , j)



CODE ::

#include <iostream>
#include <cstdio>
#include <stack>
using namespace std;
void Hanoi(int n,int i,int j,int k)
{
    stack<int>st;
    st.push(n);
    st.push(i);
    st.push(j);
    st.push(k);

    while(!st.empty())
    {
        k = st.top(); st.pop();
        j = st.top(); st.pop();
        i = st.top(); st.pop();
        n = st.top(); st.pop();

        if(n==1)
            printf("Move the top disk from pole %d to pole %d\n",i,k);
        else
        {
              st.push(n-1);   st.push(j);     st.push(i);   st.push(k);
                  st.push(1);     st.push(i);     st.push(j);   st.push(k);
                  st.push(n-1);   st.push(i);     st.push(k);   st.push(j);

        }
    }
}
int main()
{
    Hanoi(4,1,2,3);
    return 0;
}
 

No comments:

Post a Comment