Advertisement
Jaagdish47

Tower of hanoi

Nov 23rd, 2024
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.99 KB | Source Code | 0 0
  1. Tower of hanoi
  2. 8B. Write a program to implement Tower of Hanoi problem
  3.  
  4. #include <stdio.h>
  5.  
  6. int moveCount = 0;
  7.  
  8. void towerOfHanoi(int n, char source, char destination, char auxiliary) {
  9.     if (n == 1) {
  10.         moveCount++;
  11.         printf("Move disk 1 from %c to %c\n", source, destination);
  12.         return;
  13.     }
  14.    
  15.     // Move n-1 disks from source to auxiliary
  16.     towerOfHanoi(n - 1, source, auxiliary, destination);
  17.    
  18.     // Move the nth disk from source to destination
  19.     moveCount++;
  20.     printf("Move disk %d from %c to %c\n", n, source, destination);
  21.    
  22.     // Move n-1 disks from auxiliary to destination
  23.     towerOfHanoi(n - 1, auxiliary, destination, source);
  24. }
  25.  
  26. int main() {
  27.     int n;
  28.     printf("Enter the number of disks: ");
  29.     scanf("%d", &n);
  30.    
  31.     printf("Steps to solve Tower of Hanoi for %d disks:\n", n);
  32.     towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods
  33.     printf("Total moves: %d\n", moveCount);
  34.    
  35.     return 0;
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement