Hanoi Tower Question

Alright so I've got the formula fine based off http://en.wikipedia.org/wiki/Tower_of_Hanoi#Recursive_solution.

But the Actual Hanoi function itself is confusing me a little - so I was wondering if anyone could give a simple line by line comment on exactly what is happening.

Here's my Hanoi function I would like someone to comment line by line if possible.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <conio.h>
#include <stdio.h>
#include <windows.h>

void Hanoi( int numOfDisks, char source, char dest, char by );

void main()
{
	char tower1 = 'A';
	char tower2 = 'B';
	char tower3 = 'C';

	int numberOfDisks;

	printf("Enter the no. of disks on Tower A:");
	scanf_s("%d",&numberOfDisks);

	Hanoi( numberOfDisks, tower1, tower2, tower3 );

	_getch();
}

void Hanoi( int numOfDisks, char source, char dest, char by )
{
	static int step = 0;

	if( numOfDisks == 1 )
	{
		step++;
		printf("Step Number - %d - Move a plate from Tower %c, to Tower %c.\n", step, source, dest);
	}
	else
	{
		Hanoi(numOfDisks-1, source, by, dest);
		Hanoi(1, source, dest, by);
		Hanoi(numOfDisks-1, by, dest, source);
	}
}


Thanks,
Myth.

[EDIT] Code didn't line up for some reason so I fixed it up.
Last edited on
Does it work?
Yeah works perfect.
play with it, something visual... there was a game somewhere but if you don't find it cut some paper 3 or 4 pieces and try to arange them on your table.
When you run it , doesn't it tell you from which tower it is selecting the disc and to which tower it is depositing the disc. There in is the explanation of the last 3 lines.
I know how to do the puzzle - That's not an issue I can see how it works. I just don't exactly understand what the last 3 lines are doing. If it's always -1'ing wouldn't you eventually get into the minus numbers though and the program wouldn't stop? That's where I'm confused?
It's a classic recursive algorithm. The three lines say:
1. Move all but the bottom disk on A to C
2. Move the bottom disk on A to B
3. Move all the disks from B to C
That was more like the answer i was looking for. Thanks heaps kbw!
Topic archived. No new replies allowed.