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. Subnetting

    Subnet Addressing To better utilize IP address Subnet addressing introduces another hierarchical(分层) ...

  2. BindingException: Invalid bound statement (not found)问题排查:SpringBoot集成Mybatis重点分析

    重构代码,方法抛出异常:BindingException: Invalid bound statement (not found) 提示信息很明显:mybatis没有提供某方法 先不解释问题原因和排查 ...

  3. C# 泛型的协变和逆变 (转载)

    1. 可变性的类型:协变性和逆变性 可变性是以一种类型安全的方式,将一个对象当做另一个对象来使用.如果不能将一个类型替换为另一个类型,那么这个类型就称之为:不变量. 协变和逆变是两个相互对立的概念: ...

  4. input输入框中list属性不能没有效果

    网页代码入下,就是出不来效果. 人物:zslsww 解决办法: 将option中的value属性去掉: 张山李四王五爪留 显示效果,问题得到解决.

  5. oracle计算某个表中数据所占表空间的比例

    要求计算某个表所占表空间的大小,网上查了些资料用到了oracle的3个视图.具体sql如下 select segment_name as tablename, round(bytes / (selec ...

  6. SHELL脚本简单的赋值与递增

    Count=`expr $Count + 1`;#可以在各种shell执行,其他类C的写法只能在指定的bash版本执行; 赋值不能带$, 带$相当于字符串常量了;执行脚本参考如下 #!/bin/sh ...

  7. 使用泛型与不使用泛型的Map的遍历

    https://www.cnblogs.com/fqfanqi/p/6187085.html

  8. Spark运行模式_local(本地模式)

    本地运行模式 (单机) 该模式被称为Local[N]模式,是用单机的多个线程来模拟Spark分布式计算,直接运行在本地,便于调试,通常用来验证开发出来的应用程序逻辑上有没有问题. 其中N代表可以使用N ...

  9. django基本配置项-5

    目录 BASE_DIR 项目路径 DEBUG 模式 ROOT_URLCONF DATABASES 数据库设置 国际化 静态文件 访问静态文件示例 ALLOWED_HOSTS TEMPLATES 模板设 ...

  10. linux (ubuntu)安装pycharm

    1. 下载 http://www.jetbrains.com/pycharm/download/ 选择Linux Tab,选择下载免费的Community Edition. 2. 安装PyCharm ...