双色河内塔(c/python)

来源:互联网 发布:手机优酷无网络连接 编辑:程序博客网 时间:2024/05/17 22:18

思路:和河内塔类似,采用递归
1,将n个盘子,两两(不同颜色相同大小的盘子)组成一组共n/2组(A)
2,n/2组即类似于河内塔,将n/2-1组进行河内塔操作,即把A中上面的n/2-1组划到C,此时A中存在第n/2组,C中n/2-1组(第一次河内塔操作)
3,将A中的第n/2组划到B,然后进行第二次河内塔操作,把C中的所有划到A中(此时A中有n/2-1组,B中是第n/2组)
4,将B中的第n/2组分开,即B中划一个盘子给C(此时B和C中分别存在一个盘子,分别为两种颜色的最大的一个)
5 ,循环(对A中剩余的n/2-1组 重复以上操作)

c代码

#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include<stdlib.h>void move(int disk, char sourse, char temp, char target){    if (disk == 1)    {        printf("move %c to %c\n", sourse,target);        printf("move %c to %c\n", sourse,target);    }    else    {        move(disk - 1, sourse, target, temp);        move(1, sourse, temp, target);        move(disk - 1, temp, sourse, target);    }}void move_two_color(int disk){    char sourse = 'A';    char temp = 'B';    char target = 'C';    for (int i = disk / 2; i > 1; i--)    {        move(i - 1, sourse, temp, target);        printf("move %c to %c\n", sourse, temp);        printf("move %c to %c\n", sourse, temp);        move(i - 1, target, temp, sourse);        printf("move %c to %c\n", temp, target);    }    printf("move %c to %c\n", sourse, temp);    printf("move %c to %c\n", sourse, target);}int main(){    int n;    printf("disk=");    scanf("%d", &n);    move_two_color(n);    system("pause");}

python代码

# -*- coding: utf-8 -*-"""Created on Sat Nov  4 20:22:59 2017@author: yangwenbin"""#import numpy as npdef move(disk,sourse,temp,target):    #将n-1组从A-B,第n组A-C,然后n-1组从B-C,    if disk==1:        print("move %c to %c"%(sourse,target))        print("move %c to %c"%(sourse,target))        pass    else:        move(disk-1,sourse,target,temp)        move(1,sourse,temp,target)        move(disk-1,temp,sourse,target)        pass    passdef move_two_color(disk):    sourse='A'    temp='B'    target='C'    #将disk个盘子分为disk/2组    #一次循环代表:将A柱子中的最下面的一组分配好    for i in range(int(disk)//2,1,-1):        move(i-1,sourse,temp,target) #将A中的上面n-1组分到C          print("move %c to %c\n"%(sourse,temp))  #将A中的最下面一组划到B        print("move %c to %c\n"%(sourse,temp))        move(i-1,target,temp,sourse)  #将C中的所有划分到A        print("move %c to %c\n"%(temp,target))  #将B中组的一个盘子划到C,此时第一组分好        pass    #如果只有一组则直接A到B,A到C    print("move %c to %c\n"%(sourse,temp))    print("move %c to %c\n"%(sourse,target))if __name__=="__main__":    n=input("disk=")    move_two_color(n)
原创粉丝点击