Created
May 20, 2012 05:36
-
-
Save feiskyer/2752011 to your computer and use it in GitHub Desktop.
Tower of Hanoi problem
This file contains hidden or 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 <stdio.h> | |
| #include <stdlib.h> | |
| /* | |
| * Tower of Hanoi problem | |
| * | |
| * T(n)=2T(n-1)+1 => T(n)=2^n-1 | |
| */ | |
| static int steps=0; | |
| void print_step(char src, char dst) | |
| { | |
| steps++; | |
| printf("Move top from %c to %c\n",src, dst); | |
| } | |
| void hanoi(int n, char src, char mid, char dst) | |
| { | |
| if(n==1){ | |
| print_step(src, dst); | |
| }else{ | |
| hanoi(n-1, src, dst, mid); | |
| print_step(src, dst); | |
| hanoi(n-1, mid, src, dst); | |
| } | |
| } | |
| int main(int argc, char** argv) | |
| { | |
| if(argc!=2){ | |
| printf("Usage: %s n\n",argv[0]); | |
| exit(-1); | |
| } | |
| hanoi(atoi(argv[1]),'A','B','C'); | |
| printf("%d steps\n",steps); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment