This program solves tower of Hanoi problem in minimum possible steps and outputs the moves of each step.
Sample output for 4 Discs:
Program:
#include<stdio.h> #include<conio.h> int moveCount=0; void toh(int,char,char,char); int main() { int numOfDiscs; char initialRod,finalRod,auxRod; clrscr(); printf("Please note that in the solution A,B,C are the names of the initial, aux, final peg which will hold the discs respectively.\n\n"); printf("Enter the number of discs: "); scanf("%d",&numOfDiscs); initialRod='A'; auxRod='B'; finalRod='C'; printf("\nSNo.\tMoves\n\n"); toh(numOfDiscs,initialRod,auxRod,finalRod); getch(); return 1; } void toh(int n,char initialRod,char auxRod,char finalRod) { if(n==1){ moveCount++; printf("\n%d\t%c->%c",moveCount,initialRod,finalRod); return; } toh(n-1,initialRod,finalRod,auxRod); moveCount++; printf("\n%d\t%c->%c",moveCount,initialRod,finalRod); toh(n-1,auxRod,initialRod,finalRod); }
No comments:
Post a Comment