Created
June 21, 2014 03:46
-
-
Save yao2030/6e83be27b69ea492cf1b 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 <iostream> | |
using namespace std; | |
struct Problem { | |
int n; | |
char src, mid, dest; | |
}; | |
Problem stack[200]; | |
int main(void) { | |
cin >> stack[1].n; | |
stack[1].src = 'A'; | |
stack[1].mid = 'B'; | |
stack[1].dest = 'C'; | |
int problemNum = 1; | |
while (problemNum > 0) { | |
Problem curProblem = stack[problemNum--]; | |
if (curProblem.n == 1) { | |
cout << curProblem.src << " -> " << curProblem.dest << endl; | |
} else { | |
// first problem | |
stack[++problemNum].n = curProblem.n - 1; | |
stack[problemNum].src = curProblem.mid; | |
stack[problemNum].mid = curProblem.src; | |
stack[problemNum].dest = curProblem.dest; | |
// second problem | |
stack[++problemNum].n = 1; | |
stack[problemNum].src = curProblem.src; | |
stack[problemNum].mid = curProblem.mid; | |
stack[problemNum].dest = curProblem.dest; | |
// third problem | |
stack[++problemNum].n = curProblem.n - 1; | |
stack[problemNum].src = curProblem.src; | |
stack[problemNum].mid = curProblem.dest; | |
stack[problemNum].dest = curProblem.mid; | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
implement hanoi tower without using recursion.