Implementasi Rekursi Menara Hanoi – Bahasa C

#include <stdio.h> //definisi printf,scanf
#include <conio.h> //definisi getch
#include <stdlib.h> //definisi system
#include <windows.h> //definisi Sleep

int initialize(int arr1[],int x[]);
void print(int arr1[],int arr2[],int arr3[],int x[]);
void Hanoi(int arr1[],int arr2[],int arr3[],int x[],int n,char asal,char bantu,char tujuan);

int main()
{
int n;
int arr1[100],
arr2[100],
arr3[100],
x[3] = {0,0,0};

n = initialize(arr1,x);
print(arr1,arr2,arr3,x);
Hanoi(arr1,arr2,arr3,x,n,’A’,’B’,’C’);
getch();
return 0;
}

int initialize(int arr1[],int x[]){
int n;
while (true){
system(“cls”);
printf(“= = = = | T O W E R O F H A N O I – tutorialpemrograman.wordpress.com | = = = =\n\n”);
printf(“Jumlah Kepingan : “);
if (scanf(“%d”,&n) == 1 ) break;
fflush(stdin);
}
puts(“”);
for (int i=n;i>=1;i–){
arr1[x[0]++] = i;
}
return n;
}

void print(int arr1[],int arr2[],int arr3[],int x[]){
int i,
j = 0;
for (j=0;j<3;j++){
if (j == 0)printf(“A : “);
if (j == 1)printf(“B : “);
if (j == 2)printf(“C : “);
for (i=0;i<x[j];i++){
if (j == 0) printf(“%3d”,arr1[i]);
if (j == 1) printf(“%3d”,arr2[i]);
if (j == 2) printf(“%3d”,arr3[i]);
}
printf(“\n”);
}
printf(“\n”);
}

// pindahkan piringan ke n dari asal menuju tujuan melalui bantu
void Hanoi(int arr1[],int arr2[],int arr3[],int x[],int n,char asal,char bantu,char tujuan)
{

if (n == 0) return;
//pindahkan piringan ke n-1 dari asal ke bantu melalui tonggak tujuan
Hanoi(arr1,arr2,arr3,x,n-1,asal,tujuan,bantu);

printf(“… Memindahkan kepingan ke-%d dari %c ke %c …\n\n”,n,asal,tujuan);
x[asal-65] -= 1;
switch (tujuan){
case ‘A’ :
arr1[x[0]++] = n;
break;
case ‘B’ :
arr2[x[1]++] = n;
break;
case ‘C’ :
arr3[x[2]++] = n;
break;
}
print(arr1,arr2,arr3,x);
Sleep(1000);
//pindahkan piringan ke n – 1 dari bantu menuju tujuan melalui asal
Hanoi(arr1,arr2,arr3,x,n-1,bantu,asal,tujuan);
}

http://tutorialpemrograman.wordpress.com/category/bahasa-c/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s