汉诺塔问题

1.递归算法:

  程序代码:

    void move(char x,char y)

    {

      static int count = 0;

      printf("%c -> %c",x,y);

      count++;

      if(count == 4)

      {

        printf("\n");

        count = 0;

      }

      else

        printf("\t");

    }

    void hanio(int n,char x,char y,char z)

    //把n个圆盘从塔座X移动到塔座Z的过程,Y为辅助塔座

    {

      if(n <= 0 )

        return;

      if(n == 1)

      {

        move(x,z);

        return;

      }

      hanio(n-1,x,z,y);

      move(x,z)

      hanio(n-1,y,x,z);

    }

  时间复杂度:移动n个盘子相当于移动两次n-1个盘子的时间,由数学归纳法可得该算法的时间代价为O(2n)。

  空间复杂度:主要用于实现递归的栈,深度为n,故空间代价为O(n)。  

2.非递归算法:

  数据结构:

    typedef struct 

    {

      int n;    //问题规模

      char x;   //起始塔座

      char y;   //辅助塔座

      char z;   //目标塔座

    }DataType;

  程序代码:

    void hanio_nonrecursive(int n,char x,char y,char z)

    {

      PSeqStack ps;

      DataType temp,temp2'

      if(n<=0)

        return;

      if(n == 1)

      {

        move(x,z);

        return;

      }

      ps = createEmptyStack_seq();

      temp.n = n; temp.x = x; temp.y = y; temp.z = z;

      push_seq(ps,temp);      //初状态进栈

      while(!isEmptyStack_seq(ps))

      {

        temp2 = top_seq(ps);

        pop_seq(ps);

        if(temp2.n == 1)

          move(temp2.x,temp2.z);

        else

        {

          temp.n = temp2.n-1; temp.x = temp2.y; temp.y = temp2.x; temp.z = temp2.z;

          push_seq(ps,temp);      //(n-1,y,x,z)进栈

          temp.n = 1; temp.x = temp2.x; temp.y = temp2.y; temp.z = temp2.z;

          push_seq(ps,temp);      //(1,x,y,z)进栈

          temp.n = temp2.n-1; temp.x = temp2.x; temp.y = temp2.z; temp.z = temp2.y;

          push_seq(ps,temp);      //(n-1,x,z,y)进栈

      }

    }

    free(ps);

  }

  代价分析:非递归的代价不会超过递归算法的代价。

转载于:https://www.cnblogs.com/maomaohhmm/archive/2012/09/09/2678084.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值