2016-10-26 2 views
0

3 개의 매개 변수를 사용하여 하노이 재귀 알고리즘을 작성해야합니다. 이것은 내가 가진 무엇 : N = 3내 하노이 타워 알고리즘이 작동하지 않는 이유는 무엇입니까?

#include <stdio.h> #include <stdio.h> 

void hanoi(int m, int i, int j); 
void move(int start, int end); 

int main(){ 
    int n = 0; 
    int i = 1; 
    int j = 3; 
    printf("Enter how many disks you want to move: "); 
    scanf("%d", &n); 
    int m = n; 
    hanoi(m,i,j); 

} 

void hanoi(int m, int i, int j){  
    if (m==1) 
    { 
     move(i,j); 
     return; 
    } 
    hanoi(m-1,i,2); 
    move(i,j); 
    hanoi(m-1,2,j); 

} 

void move(int start, int end){ 
    printf("A disk moves from position %d. to %d.\n", start,end); 
} 

출력은 다음

Enter how many disks you want to move: 3 
A disk moves from position 1. to 2. 
A disk moves from position 1. to 2. 
A disk moves from position 2. to 2. 
A disk moves from position 1. to 3. 
A disk moves from position 2. to 2. 
A disk moves from position 2. to 3. 
A disk moves from position 2. to 3. 

내가 다른 알고리즘 바라 보았다, 나는 그 톤이 goold 된 하노이 문제를 해결하기 위해이 알고 . 그러나, 그들은 모두 4 개의 매개 변수를 가지고 문자를 사용하지만, 숫자 만 사용하고 보조 타워 매개 변수는 내 함수에서 제외하고 싶습니다. 어떻게 해결할 수 있습니까? n = 1 및 n = 2 인 경우 알고리즘이 정상적으로 작동합니다.

+1

사용하십시오 설명 변수 이름으로 주석으로 다른 말뚝보다는 2을 사용해야합니다. –

+1

문제는 '2'가 하드 코드 된 것입니다. –

+0

@KarolyHorvath 알 겠어 ... 어떻게 우회 할 수 있니? 함수의 시작 부분에서 값 2로 변수를 연결하면 해결되지 않습니다. :/ – SoflolikeAntonio

답변

1

코드 @Karoly Horvath

void hanoi(int m, int i, int j){  
    if (m==1) { 
     move(i,j); 
     return; 
    } 
    int Other_peg = (1+2+3) - i - j; 
    hanoi(m-1,i,Other_peg); 
    move(i,j); 
    hanoi(m-1,Other_peg,j); 
} 
관련 문제