4.Hanoi塔递归算法

其实这个东西我有点看不懂,但觉得像我那么没基础的人都选择留下一部分知识点,肯定是考虑到它的实际效用相当高啦!!

输入:圆盘数n,3根细杆——源杆A,过渡杆B,目标杆C

输出:圆盘从源杆移动到目标杆过程的最少步骤序列

考虑方法,若只有一个盘子,则只要将其从源杆A移动到目标杆C就行。如果多于一个盘,先将源杆A上的前n-1个盘移动到过渡杆B上,再将留在源杆上的最大的盘移动到目标杆上,最后将过渡杆上的n-1个盘移动到目标杆上。这里考虑下多次递归,就是每次盘子从大到小递归到最后一个盘子放上目标杆就行。

算法伪代码:

1.    if n=1;

2.      then i<-PICK-TOP-DISK(current,A) //取出A杆上最小编号的盘

3.        current[i]<-C  //记录每次i盘移动到哪个杆上

4.        count<-count+1  //记录移动次数

5.        print "move",count,i,"disk:",A,"->",C

6.        return

7.    HANOI(n-1,A,C,B)     //将源杆A上的n-1个盘通过过渡杆C移动到B杆上

8.    current[n]<-C

9.    count<-count+1

10.  print "move",count,n,"disk:",A,“->”,C   //将第n个盘移动到C杆上

11.  HANOI(n-1,B,A,C)  //将源杆B上的n-1个盘通过过渡杆A移动到目标杆C上

其中PICK-TOP-DISK(current,X)   //其中X杆标号

1.    i<-1

2.    while i<=n and current[i]!=X  //盘从小编号到大编号,因为小号在上,检查该编号盘是否在X杆上

3.      do i=i+1

4.    return i  //得到该编号X杆上最小编号i盘

c++:

hanoi.h

#define _hanoi_h

#include<stdio.h>

int pickTopDisk(char *current,char x){

int i=0;

while(current[i]!=x)

i++;

return i;

}

void hanoi(char *current,int n,char A,char B,char C){

static int count=0;

int i=0;

if(n==1){

i=pickTopDisk(current,A);

current[i]=C;

count++;

printf("move %d disk %d:%c->%c\n",count,i+1,A,C);

return;

}

hanoi(current,n-1,A,C,B);

current[n-1]=C;

count++;

printf("move %d disk %d:%c->%c\n",count,n,A,C);

hanoi(current,n-1,B,A,C);

}

main.cpp

#include<stdlib.h>

#include"hanoi.h"

int main(){

char current[]={'A','A','A','A'};

char A='A',B='B',C='C';

hanoi(current,4,A,B,C);

}

JAVA:

Hanoi.java

package test;

public class Hanoi {

public static int count;

public static void hanoi(char[] current,int n,char A,char B,char C) {

if(n==1) {

int i=0;

i=pickTopDisk(current,A);

current[i]=C;

count++;

System.out.println("move"+count+"disk"+n+":"+A+"->"+C);

return;

}

hanoi(current,n-1,A,C,B);

current[n-1]=C;

count++;

System.out.println("move"+count+"disk"+n+":"+A+"->"+C);

hanoi(current,n-1,B,A,C);

}

private static int pickTopDisk(char[] current,char x) {

int i=0;

while(current[i]!=x)

i++;

return i;

}

}

Test.java

package test;

//基本上hanoi只要改下下面的数据就能用

public class Test{

public static void main(String[] args){

Hanoi.count=0;

char[] current= {'A','A','A','A'};//只要将一开始圆盘位置数组代入

char A='A',B='B',C='C';//开始时源杆,过渡杆,目标杆标号

Hanoi.hanoi(current,4,A,B,C);//其中4表示有4个圆盘

}

}

猜你喜欢

转载自blog.csdn.net/weixin_39653545/article/details/82842496