Created
April 26, 2023 05:52
-
-
Save modos/977b2cfa5edbfb7141a698dad893dccb to your computer and use it in GitHub Desktop.
برج هانوی
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<bits/stdc++.h> | |
using namespace std; | |
int cnt = 1; | |
void hanoi(char from, char to, char help, int n){ | |
if(n == 1){ /// exit condition | |
/// base case | |
/// move the only disk from 'from' to 'to' | |
cout << cnt++ << ' ' << from << ' ' << to << '\n'; | |
return; | |
} | |
/// n != 1 Recursion case | |
/// move n-1 disk from 'from' to 'help' | |
hanoi(from, help, to, n-1); | |
/// move the n-th disk from 'from' to 'to' | |
cout << cnt++ << ' ' << from << ' ' << to << '\n'; | |
/// move n-1 disk from 'help' to 'to' | |
hanoi(help, to, from, n-1); | |
} | |
int main(){ | |
int n; | |
cin >> n; /// input | |
hanoi('A', 'B', 'BC', n); /// move n disk from 'A' to 'B' | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment