Created
January 25, 2022 20:31
-
-
Save dakerfp/9ab3ee8931de20dfc3d9642d477c9ac3 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 <stack> | |
#include <cassert> | |
using namespace std; | |
namespace hanoi { | |
static void move(stack<int>& from, stack<int>& to) | |
{ | |
assert(!from.empty()); | |
assert(to.empty() || to.top() > from.top()); | |
to.push(from.top()); | |
from.pop(); | |
} | |
static void move_substack(stack<int>& from, stack<int>& to, stack<int>& temp, int depth) | |
{ | |
if (depth <= 0) | |
return; | |
move_substack(from, temp, to, depth - 1); | |
move(from, to); | |
move_substack(temp, to, from, depth - 1); | |
} | |
static void move(stack<int>& from, stack<int>& to, stack<int>& temp) | |
{ | |
move_substack(from, to, temp, from.size()); | |
} | |
} | |
int main() | |
{ | |
stack<int> from, to, temp; | |
for (int i = 5; i >= 1; i--) | |
from.push(i); | |
hanoi::move(from, to, temp); | |
assert(from.empty()); | |
assert(temp.empty()); | |
for (int i = 1; i <= 5; i++) { | |
assert(to.top() == i); | |
to.pop(); | |
} | |
assert(to.empty()); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment