Description

In the classic problem of Towers of Hanoi, you have 3 towers 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 (i.e., each disk sits on top of an even larger one). You have the following constraints:

  1. Only one disk can be moved at a time.
  2. A disk is slid off the top of one tower onto the next tower.
  3. A disk can only be placed on the top of a larger disk.

Write a program to move the disks from the first tower to the last using stacks.

解题:本题是经典的汉诺塔问题,只要想好移动的顺序,还是挺简单的。分为三个塔:原塔(初始化n个盘子),目标塔,缓冲塔。思路是,借助目标塔(此时目标塔充当缓冲塔),先把前n-1个盘子移动到缓冲塔。然后把最后一个移动到目标塔。接着,借助原塔,把缓冲塔的盘子移动到目标塔,递归执行。代码如下:

public class Tower {
private Stack<Integer> disks;
/*
* @param i: An integer from 0 to 2
*/
public Tower(int i) {
// create three towers
disks = new Stack<Integer>();
} /*
* @param d: An integer
* @return: nothing
*/
public void add(int d) {
// Add a disk into this tower
if (!disks.isEmpty() && disks.peek() <= d) {
System.out.println("Error placing disk " + d);
} else {
disks.push(d);
}
} /*
* @param t: a tower
* @return: nothing
*/
public void moveTopTo(Tower t) {
// Move the top disk of this tower to the top of t.
int temp = this.getDisks().pop();
t.add(temp);
} /*
* @param n: An integer
* @param destination: a tower
* @param buffer: a tower
* @return: nothing
*/
public void moveDisks(int n, Tower destination, Tower buffer) {
// Move n Disks from this tower to destination by buffer tower
if(n == 1){
this.moveTopTo(destination);
}else{
this.moveDisks(n-1 , buffer, destination);
this.moveTopTo(destination);
buffer.moveDisks(n-1, destination, this);
} } /*
* @return: Disks
*/
public Stack<Integer> getDisks() {
// write your code here
return disks;
}
} /**
* Your Tower object will be instantiated and called as such:
* Tower[] towers = new Tower[3];
* for (int i = 0; i < 3; i++) towers[i] = new Tower(i);
* for (int i = n - 1; i >= 0; i--) towers[0].add(i);
* towers[0].moveDisks(n, towers[2], towers[1]);
* print towers[0], towers[1], towers[2]
*/

227. Mock Hanoi Tower by Stacks【LintCode java】的更多相关文章

  1. 227. Mock Hanoi Tower by Stacks【easy】

    In the classic problem of Towers of Hanoi, you have 3 towers and N disks of different sizes which ca ...

  2. Lintcode227 Mock Hanoi Tower by Stacks solution 题解

    [题目描述] In the classic problem of Towers of Hanoi, you have 3 towers and N disks of different sizes w ...

  3. 451. Swap Nodes in Pairs【LintCode java】

    Description Given a linked list, swap every two adjacent nodes and return its head. Example Given 1- ...

  4. 445. Cosine Similarity【LintCode java】

    Description Cosine similarity is a measure of similarity between two vectors of an inner product spa ...

  5. 433. Number of Islands【LintCode java】

    Description Given a boolean 2D matrix, 0 is represented as the sea, 1 is represented as the island. ...

  6. 423. Valid Parentheses【LintCode java】

    Description Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine ...

  7. 422. Length of Last Word【LintCode java】

    Description Given a string s consists of upper/lower-case alphabets and empty space characters ' ', ...

  8. 420. Count and Say【LintCode java】

    Description The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, ...

  9. 415. Valid Palindrome【LintCode java】

    Description Given a string, determine if it is a palindrome, considering only alphanumeric character ...

随机推荐

  1. enmu枚举类型

    在实际问题中,有些变量的取值被限定在一个有限的范围内.例如,一个星期内只有七天,一年只有十二个月,一个班每周有六门课程等等.如果把这些量说明为整型,字符型或其它类型显然是不妥当的.为此,C语言提供了一 ...

  2. linux VMware使用

    contos7 配置网络 使用NAT模式连接本地网络 进入Linux机器配置网络 vi /etc/sysconfig/network-scripts/ifcfg-eth0 TYPE=EthernetP ...

  3. java中匿名内部类总结

    在java的世界里,提供了匿名内部类语法糖,用于帮助大家简化代码,本文简要从接口,抽象类以及常规类以代码的形式描述其常用模式. 1. 接口模式 public interface IWriter { v ...

  4. 为什么我们需要DTO?

    最近在写代码时突然产生了这个疑惑,我们为什么需要DTO进行数据传输呢? 要了解DTO首先我们要知道什么是DAO,DAO就是数据库的一个数据模型,是一个类文件里面存储着数据库的字段及其getter&am ...

  5. 一站式学习Redis 从入门到高可用分布式实践

    1:redis 是用c语言来实现的,速度快 持久化 单线程 复杂的数据类型有bitmap和hyperloglog和geo地理信息2:高可用.分布式 v2.8开始支持Redis-Sentinel(哨兵) ...

  6. MAMP:MySQL wasn't able to start

    MAMP 我点击start server的时候 发现mysql服务器打不开 http://images.cnblogs.com/cnblogs_com/lwwen/1231721/o_11111111 ...

  7. mysql 8.0.12安装步骤

    首先从官网下载压缩包: 解压压缩包到指定目录,在目录下新建my.ini,配置内容如下; [mysqld]  # 设置3306端口  port=3306  # 设置mysql的安装目录  basedir ...

  8. Jquery中绑定事件与普通事件的区别

    (“#panel”).bind(“click”,function(){ 与$(“#panel”).click(function(){ 有什么区别 ? 绑定可以同时加多个事件 如:$(“#panel”) ...

  9. 使用ContentType处理大量的外键关系

    问题分析 在之前的一个商城的项目中使用了mysql, 提到mysql就是外键, 多对多等等一系列的表关系 因为是一个商城的项目, 这里面有优惠券, 商品有很多的分类, 不同的商品又有不同的优惠券 其实 ...

  10. Altium Designer 快捷键与技巧

    在PCB中: 布线过程中,换层快捷键:"Ctrl"  + "Shift" + "滚轮". 单独显示顶层或底层:按"SHIFT&qu ...