zoukankan      html  css  js  c++  java
  • One usage of recurison: the tower of Hanoi

    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-Hill
    
    
    public 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.
    





  • 相关阅读:
    【Codeforces Round #645 (Div. 2) F】 Tasty Cookie
    【Codeforces Round #645 (Div. 2) E】 Are You Fired?
    【Educational Codeforces Round 88 (Rated for Div. 2) C】 Mixing Water
    20191114-4 Beta发布用户使用报告
    20191114-3 Beta阶段贡献分配
    beta发布
    20191107-1 每周例行报告
    beta 2/2 阶段中间产物提交入口
    beta week 2/2 Scrum立会报告+燃尽图 07
    beta week 2/2 Scrum立会报告+燃尽图 06
  • 原文地址:https://www.cnblogs.com/gavanwanggw/p/7223589.html
Copyright © 2011-2022 走看看