Semplice esercizio in c++ per dimostrare il comportamento ricorsivo di un algoritmo per risolvere la torre di hanoi nel minor numero possibile di mosse.
PHP Code:
//
// main.cpp
// Test
//
// Created by Giovanni Di Grezia on 22/07/13.
// Copyright (c) 2013 Giovanni Di Grezia. All rights reserved.
//
#include <iostream>
#include <string>
usingnamespacestd;
void hanoi (int blocks, int orig, int dest, int support, int * counter);
int main(void) {
int disks;
cout << "Enter the number of disks" << endl;
cin >> disks;
int counter = 0;
hanoi(disks,1,3,2,&counter);
cout << "Completed in " << counter << " passes" << endl;
return 0;
}
void hanoi (int blocks, int orig, int dest, int support, int * counter){
if (blocks == 1){
cout << "Move from " << orig << " to " << dest << endl;
(*counter)++ ;
} else {
hanoi(blocks - 1, orig, support, dest, counter);
cout << "Move from " << orig << " to " << dest << endl;
(*counter)++;
hanoi(blocks - 1, support, dest, orig, counter);
}
}