发布网友 发布时间:2024-10-07 12:42
共1个回答
热心网友 时间:2024-10-22 09:49
汉诺塔问题是程序设计中的经典递归问题。 算法思路: 1.如果只有一个金片,则把该金片从源移动到目标棒,结束。 2.如果有n个金片,则把前n-1个金片移动到辅助的棒,然后把自己移动到目标棒,最后再把前n-1个移动到目标棒 补充:汉诺塔的算法实现(c++) #include <fstream> #include <iostream> using namespace std; ofstream fout("out.txt"); void Move(int n,char x,char y) { fout<<"把"<<n<<"号从"<<x<<"挪动到"<<y<<endl; } void Hannoi(int n,char a,char b,char c) { if(n==1) Move(1,a,c); else { Hannoi(n-1,a,c,b); Move(n,a,c); Hannoi(n-1,b,a,c); } } int main() { fout<<"以下是7层汉诺塔的解法:"<<endl; Hannoi(7,'a','b','c'); fout.close(); cout<<"输出完毕!"<<endl; return 0; } C语言精简算法 /* Copyrighter by SS7E */ #include<stdio.h> /* Copyrighter by SS7E */ void hanoi(int n,char A,char B,char C) /* Copyrighter by SS7E */ { if(n==1) { printf("Move disk %d from %c to %c\n",n,A,C); } else { hanoi(n-1,A,C,B); /* Copyrighter by SS7E */ printf("Move disk %d from %c to %c\n",n,A,C); hanoi(n-1,B,A,C); /* Copyrighter by SS7E */ } } main() /* Copyrighter by SS7E */ { int n; printf("请输入数字n以解决n阶汉诺塔问题:\n"); scanf("%d",&n); hanoi(n,'A','B','C'); }/* Copyrighter by SS7E */ PHP算法: <?php function hanoi($n,$x,$y,$z){ if($n==1){ move($x,1,$z); }else{ hanoi($n-1,$x,$z,$y); move($x,$n,$z); hanoi($n-1,$y,$x,$z); } } function move($x,$n,$z){ echo 'move disk '.$n.' from '.$x.' to '.$z.'<br>'; } hanoi(10,'x','y','z'); ?> JAVA算法: public class Haniojava { public static void main(String args[]) { byte n=2; char a='A',b='B',c='C'; hanio(n,a,b,c); } public static void hanio(byte n,char a,char b,char c) { if(n==1) System.out.println("move "+a+" to "+b); else { hanio((byte)(n-1),a,c,b); System.out.println("move "+a+" to "+b); hanio((byte)(n-1),c,b,a); } } }