C-language recursive implementation of Hanoi algorithm

Source: Internet
Author: User
Tags printf

Hanoi's recursive implementation algorithm, the disc A in the use of B disk completely moved to the C disk,

Only one disc can be moved at a time, and the market cannot be placed on a small disk each time it moves

The pseudo algorithm for recursive functions is as follows:

if (n = = 1)

Move the disc on column A directly from A to C

Else

First, the N-1 disc on column A is moved to Pillar B with the help of column C.

Move the nth disc directly on column A to pillar C.

Finally, the n-1 disc on pillar B is moved to pillar C with the help of a pillar.

The time complexity of the recursive algorithm is O (2 n-th side), when there are N-disk, you need to move the disk 2 of the n-th-1 times

Operating system: Ubuntu

Compiling software: GCC

Results screenshot:

Source:

#include <stdio.h>  
      
void Move (Int,char,char,char);  
      
int main ()  
{  
//a, B, C, respectively, represents three columns  
char ch1 = ' A ';  
Char CH2 = ' B ';   
char CH3 = ' C ';   
      
n represents the number of disks  
int n;  
printf ("Please enter the number of discs:");  
scanf ("%d", &n);  
Move (N,CH1,CH2,CH3);  
      
return 0;  
}  
      
To move n discs from X pillars to Z pillars with the y pillar  
void motion (int n,char X,char Y,char z)  
{  
if (n = 1)  
  printf ("Disk number%d: Moving from%c to% C\n ", n,x,z);  
else
{move  
  (n-1,x,z,y);  
  printf ("Disk number%d: Moving from%c to%c\n", n,x,z);  
  Move (n-1,y,x,z);  
}  
}

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.