DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Tower Of Hanoi

09.28.2007
| 4031 views |
  • submit to reddit
        Solves the old "Tower of Hanoi" problem using a recursive divide et impera approach.

http://en.wikipedia.org/wiki/Tower_of_Hanoi

#include <stdio.h>

void hanoi(int n, char a, char b, char c) {
	if (!n)	
		return;
	
	hanoi(n - 1, a, c, b);
	printf("%c -> %c\n", a, b);
	hanoi(n - 1, c, b, a);
}

int main(int argc, char *argv[]) {
	int n = 3;
	hanoi(n, 'a', 'b', 'c');
	
	return 0;
}