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. platform平台总线

    一.何为平台总线 (1)相对于usb.pci.i2c等物理总线来说,platform总线是虚拟的.抽象出来的.(2)CPU与外部通信的2种方式:地址总线式连接和专用协议类接口式连接.平台总线,是扩展到 ...

  2. Oracle 体系结构二 内存结构

    Oracle实例由共享内存块(SGA)以及大量的后台进程构成. SGA必须包含的数据结构: 数据库缓冲区缓存 日志缓冲区 共享池 可选的数据结构: 大池 JAVA池 流池 其他缓冲区缓存池 用户会话还 ...

  3. App升级iOS7体会

    本文转自App升级iOS7体会. xcode5 GM版已经发布,虽然还是pre-release版,但离最终版不远了.对于没有用到新特性的app面临的最大问题就是UI的变化.Apple提供了UI Tra ...

  4. android软件开发基础

    1.android特性:开放性:开源的一个基础, 方便性: 平等性: 2.Android四大基本组件分别是Activity,Service服务,Content Provider内容提供者,Broadc ...

  5. IPC进程间通信---共享内存

    共享内存 共享内存:共享内存就是分配一块能被其它进程访问的内存.每个共享内存段在内核中维护着一个内部结构shmid_ds, 该结构定义在头文件linux/shm.h中,其结构如下: struct sh ...

  6. df du sync

    df命令用来检查linux系统的磁盘空间占用情况 df [选项] -h:以容易理解的格式输出文件系统分区占用情况,如32KB,120MB,60GB -k:以KB大小单位输出文件系统分区占用情况 -m: ...

  7. Zabbix——使用邮件报警

    前提条件: 1. Zabbix版本4.0 zabbix-server 命令配置: yum install mailx -y #下载邮件功能 vi /etc/mail.rc set bsdcompat ...

  8. TinyMCE插件:RESPONSIVE filemanager 9 文件名统一格式化

    上传图片方法(filemanager/UploadHandler.php) 在上传图片的函数中查看,发现$file->name是一个完整的[文件名.后缀名],所以使用explode(),文件名和 ...

  9. 3. HTML中的容器标签

    什么是容器标签?在HTML开发中我们常常会使用一类标签作为容器放置一些内容,我们把这类标签称之为容器标签,可以作为容器标签的包括列表标签.表格标签.框架标签.布局标签,在这里我们就来总结下这些内容. ...

  10. hadoop jobhistory访问界面长时间打不开

    1.浏览器无法直接通过url访问 可能原因 :主机名未配置,因此无法识别,在 c:\windows\system32\drivers\etc 目录添加主机名和对应ip hostname1[主机名 ] ...