Recursively solve towers of hanoi - C++ Data Structure

C++ examples for Data Structure:Algorithm

Description

Recursively solve towers of hanoi

Demo Code

#include <iostream>

void hanoi(int, int, int, int);

int main(int argc, const char *argv[]) {
    hanoi(4, 1, 3, 2);//w  w  w  .j  av  a  2  s.c  o m

    return 0;
}
void hanoi(int numDisks, int sourcePeg, int destPeg, int tempPeg) {
    if (numDisks > 0) {
        hanoi((numDisks - 1), sourcePeg, tempPeg, destPeg);
        std::cout << "From " << sourcePeg << " to " << destPeg << std::endl;

        hanoi((numDisks - 1), tempPeg, destPeg, sourcePeg);
    }
}

Result


Related Tutorials