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. CSU - 1224 ACM小组的古怪象棋

    传送门: http://acm.csu.edu.cn/csuoj/problemset/problem?pid=1224 1224: ACM小组的古怪象棋 Lime Limit: 1 Sec     ...

  2. <a>标签跳转到Servelet页面并实现参数的传递

    <a>标签跳转到页面不能通过request.setAttribute()和getAttribute()方法获取参数. <a>标签只能通过request.getParameter ...

  3. Flex入坑指南

    弹性布局flex是一个几年前的CSS属性了,说它解放了一部分生产力不为过.至少解放了不少CSS布局相关的面试题 :) 之前网上流行的各种XX布局,什么postion: absolute+margin, ...

  4. 若是将Map作为Key,存入Redis,该如何操作?

    1.先封装HashMap Map<String,Object> map=new HashMap<String,Object>(); map.put("name&quo ...

  5. GPUImage源码解读之GPUImageFramebufferCache

    简介 由于GPUImage添加滤镜可以形成一个FilterChain,因此,在渲染的过程中,可能会需要很多个FrameBuffer,但是正如上文所说,每生成一个FrameBuffer都需要占用一定的内 ...

  6. 复习宝典之SpringMVC

    查看更多宝典,请点击<金三银四,你的专属面试宝典> 第七章:SpringMVC MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(co ...

  7. MySQL常用参数说明(持续更新)

      ##innodb correlate   innodb_flush_log_at_trx_commit value: 0,[1],2 effect: control the flush opera ...

  8. shazam音乐检索算法 附完整c代码

    在讲算法之前,上一些前人的资料. http://coding-geek.com/how-shazam-works/ https://laplacian.wordpress.com/2009/01/10 ...

  9. JavaWeb——库存管理系统(1)jsp部分---18.12.13

    add.jsp <%@ page language="java" contentType="text/html; charset=UTF-8"    pa ...

  10. 为什么我要放弃javaScript数据结构与算法(第十一章)—— 算法模式

    本章将会学习递归.动态规划和贪心算法. 第十一章 算法模式 递归 递归是一种解决问题的方法,它解决问题的各个小部分,直到解决最初的大问题.递归通常涉及函数调用自身. 递归函数是像下面能够直接调用自身的 ...