博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
One usage of recurison: the tower of Hanoi
阅读量:6656 次
发布时间:2019-06-25

本文共 1814 字,大约阅读时间需要 6 分钟。

Statements: This blog was written by me, but most of content  is quoted from book【Data Structure with Java Hubbard】 

【Description】

  we have seen important examples of functions that are more naturally defined and more easily understood by using recursion. Foe some problem, recursion is the only reasonable method of solution.The towers of hanoi puzzle is a classical example of a problem whose solution demands recursion. The game consists of a board with three vertical pegs labeled A, B, and C, and a sequence of n disks with holes in their centers. The radii of the disks are in an arithmetic progression(eg,6cm, 7cm, 8cm); and are mounted on peg A. The rule is that no disk may be above a smaller disk on the same peg. The objective of the game is to move all the disks from peg A to peg C, one disk at a time, without violating the rule. 

【Implement】

The program prints the solution to the towers of Hanoi problem of moving three disk from peg A to peg C via Peg B. 
package com.albertshao.ds.recursion;//  Data Structures with Java, Second Edition//  by John R. Hubbard//  Copyright 2007 by McGraw-Hillpublic class TestHanoiTowers {  public static void main(String[] args) {    HanoiTowers(3, 'A', 'B', 'C');  }    public static void HanoiTowers(int n, char x, char y, char z) {    if (n==1) {                // basis      System.out.printf("Move top disk from peg %c to peg %c.%n", x, z);    } else {                    HanoiTowers(n-1, x, z, y);  // recursion      HanoiTowers(1, x, y, z);    // recursion        HanoiTowers(n-1, y, x, z);  // recursion    }  }}

【Result】

Move top disk from peg A to peg C.Move top disk from peg A to peg B.Move top disk from peg C to peg B.Move top disk from peg A to peg C.Move top disk from peg B to peg A.Move top disk from peg B to peg C.Move top disk from peg A to peg C.

你可能感兴趣的文章
深入理解最强桌面地图控件GMAP.NET --- 初识
查看>>
使用okhttp连接网络,再把数据储存进Sqlite
查看>>
20155318 20155328 20155333 《信息安全技术》第三次实验 实验报告
查看>>
Android基于mAppWidget实现手绘地图(八)–获取用户地理位置
查看>>
C++ 单向链表反转
查看>>
使用Nginx的必备软件以及Linux内核参数的优化
查看>>
Git分布式版本控制工具(汇总目录)
查看>>
IETF和W3C的区别
查看>>
docker
查看>>
Date13
查看>>
HTML5新增了哪些标签
查看>>
网站DDOS***防护实战老男孩经验心得分享
查看>>
X86服务器虚拟化的资源划分和性能优化
查看>>
2015年11月 广州深圳 MVP 线下活动
查看>>
⑨①-成功者的路永远都是相通的
查看>>
一次DPM备份Exchange DAG的故障处理过程
查看>>
Docker视频发布
查看>>
利用Powershell查询AD中账号属性
查看>>
office2003/2007/2010版本降低宏安全设置方法
查看>>
高性能的MySQL(7)字符集和校对
查看>>