2016-01-20 83 views
0
// Tower of Hanoi 
#include <stdio.h> 

void towers(int, char, char, char); 

int main() 
{ 
    int num; 
    clrscr(); 
    printf("Enter the number of disks : "); 
    scanf("%d", &num); 
    printf("The sequence of moves involved in the Tower of Hanoi are :\n"); 
    towers(num, 'A', 'C', 'B'); 
    getch(); 
    return 0; 
} 

void towers(int num, char frompeg, char topeg, char auxpeg) 
{ 
    if (num == 1) { 
     printf("\n Move disk 1 from peg %c to peg %c", frompeg, topeg); 
     return; 
    } 
    towers(num - 1, frompeg, auxpeg, topeg); 
    printf("\n Move disk %d from peg %c to peg %c", num, frompeg, topeg); 
    towers(num - 1, auxpeg, topeg, frompeg); 
    getch(); 
} 

我跑这段代码,输出是正确的,但我不明白这个递归。请给我解释一下:}谢谢:]任何人都可以解释我在C语言河内塔的递归吗?

回答

1

towers一个合理的意见是:

移动NUM光盘从PEG frompeg盯住topeg(其余的PEG是auxpeg

然后递归部分说:

  1. 移动NUM-1由PEG frompeg光盘钉住auxpeg(其余栓钉topeg由PEG frompeg

  2. 移动盘钉住topeg

  3. 移动NUM-1光盘由PEG auxpeg钉住topeg(其余栓钉frompeg