码迷,mamicode.com
首页 > 其他好文 > 详细

CC150 3.4

时间:2014-11-25 02:00:22      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:interview

3.4 In the classic problem of the Towers of Hanoi, you have 3 rods and N disks of different sizes which can slide onto any tower. The puzzle starts with disks sorted in ascending order of size from top to bottom (e.g., each disk sits on top of an even larger one). You have the following constraints: (A) Only one disk can be moved at a time. (B) A disk is slid off the top of one rod onto the next rod. (C) A disk can only be placed on top of a larger disk. Write a program to move the disks from the first rod to the last using Stacks.

class Hanoi
{
  void init();
  
  void resolve()
  {
    // Resolve (N) is:
    // Move (N-1) to stack2
    // Move Nth to stack3
    // Move (N-1) to stack3
    
    move(n , a, c, b);
  }
  
  void move(int n, Disk a, Disk b, Disk c) // A to B, using C
  {
    if (n == 1)
      b.push(a.pop());
    
    move(n - 1, a, c, b);
    b.push(a.pop());
    move(n - 1, c, b, a);
  }
}


CC150 3.4

标签:interview

原文地址:http://7371901.blog.51cto.com/7361901/1582223

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!