2016-01-20 28 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

相關問題