Data structure--Hanoi recursive Java implementation

Source: Internet
Author: User

1 /*Hanoi recursion2 * 1.0-n-1 the number of discs, move from tower A to top B3 * 2. Move the 1 discs of number n from a to the top of C4 * 3. Finally, move the N-1 disc above B to the top of C.5 * Note: The plate is numbered from top to bottom 1-n6  * */7  Public classhannotower_recursion {8 9      Public Static voidMain (string[] args) {Ten         intNdisk = 3; OneDotowers (Ndisk, ' A ', ' B ', ' C '); A  -     } -  the     Private Static voidDotowers (intTopN,CharFromCharInterCharTo ) { -         if(TopN = = 1){ -             //only one plate is numbered 1, moving directly from A to C. -System.out.println (' Disk 1 ' + ' from ' + from + ' to ' +to ); +         } -         Else{ +             //move the first N-1 plate from A to b---from-->inter ADotowers (topN-1, from, to, inter); at             //Move the nth plate from A to c---from-->to -System.out.println (' Disk ' + TopN + ' from ' + from + ' to ' +to ); -             //move the first N-1 plate from B to c---inter-->to -Dotowers (topN-1, Inter, from,to); -         } -     } in  -}

Execution process and Results

Enter (3 disks,a B C)

Enter (2 disks,a,c,b)

Enter (1disk,a B C)

Base Case-->disk1 from a---c//disk 1 from A to C

Return (1disk A B C)

Move Disk 2 from A--b//disk 2from A to B

Enter (1disk, C,a,b)

Base Case-->disk1 from c---b//disk 1 from c to B

Return (1disk C A B)

Return (2disk A C B)

Move Disk 3 from A--c//disk 3from A to C

Enter (2disk B A C)

Enter (1disk B C A)

Base Case-->disk1 from B---a//disk 1 from B to A

Return (1disk B C A)

Move Disk 2 from B--c//disk 2from B to C

Enter (1disk A B C)

Base Case-->disk1 from a---c//disk 1 from A to C

Return (1disk A B C)

Return (2disk B A C)

Return (3 disks,a B C)

Data structure--Hanoi recursive Java implementation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.