20th
Июн

Задача о Ханойских башнях. Си.

Posted by bullvinkle under Топик-обзор

Каждый студент-программист решает эту задачу. Вот код для упрощения поиска.

Код:

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

void DisplayPin(int,int);
void TransferInNext( int,int,int,int);
void InputPin(int);
void Swap(int,int);

struct Pin
{
	int pin[3][50];
	int count[3];
}T;
int count=0;
int main()
{
	int amount;
   clrscr();
	printf("Input amount rings->");
   scanf("%d",&amount);
	if(amount>50)
	{
		printf("<50\n");
		return 1;
	}
	InputPin(amount);
	if(amount)
		TransferInNext( 1,3,2,amount);
	printf("\nAmount step %d \n",count);
   getch();
	return 0;
}

void DisplayPin( int from,int to)
{
	int i,j;
	printf("\nMove Disk From %d To %d",from,to);
	for(i = 0; i < 3; i++)
	{
		printf("\n");
		printf("| ");
		for(j = 0;j< T.count; j++)
			printf("%d",T.pin[j]);
	}
	printf("\n");
}
void Swap(int from,int to)
{
	T.pin[to-1][T.count[to-1]++]=T.pin[from-1][--T.count[from-1]];
	DisplayPin(from,to);
	count++;
}
//////////////////////////////////
void TransferInNext ( int from,int to,int via,int n)
{
    if(n==1)
    {
        Swap(from,to);
    }
    else
    {
        TransferInNext(from,via,to,n-1);
        Swap(from,to);
        TransferInNext(via,to,from,n-1);
    }
}
///////////////////////////////////
void InputPin(int len)
{
	int i,k=len;
	printf("| ");
	for(i=0; i<len; i++,k--)
	{
		T.pin[0]=k;
		printf("%d",T.pin[0]);
	}
	printf("\n| \n| \n---------------------------------------\n\n");
	T.count[0]=len;
	return;
}

Возможно, в теме на форуме будет доработан код для псевдографики.

Похожие статьи

Теги: