我需要编写一个带有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);
}
n = 3的输出如下:
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.
我查看了其他算法,我知道有很多算法用来解决这个古老的河内问题。但是,它们都有4个参数并使用字符,而我只想使用数字并在我的函数中省略辅助塔参数。我该如何解决?对于n = 1和n = 2,算法工作正常。
答案 0 :(得分:1)
代码需要使用其他 peg,而不是@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);
}
MyAdapter adapter = new MyAdapter(MyFragment fragmentA,...);