'C Tower of Hanoi,
I wrote the code, but I don't understand why it works. For example, when Hanoi is recursively called the second time (on pythontutor.com's C visualization):
disk - 1 = 1, start = 1, end = 3, and temp = 2.
I think it should be: disk - 1 = 1, start = 1, end (which is now temp) = 2, and temp (which is now end) = 3.
Why is my assumption about the arguments of the function wrong? I was playing around with the order of the last three lines of code in the Hanoi function when it printed out the correct answer, so I don't know how I did it. I appreciate any help you can provide.
#include <stdio.h> //inputs and more
void hanoi(int disks, int start, int end, int temp);
int main(void)
{
int d = 3, s = 1, e = 3, t = 2;
hanoi(d, s, e, t);
return 0;
}//end of main function
void hanoi(int disks, int start, int end, int temp)
{
if (1 == disks)
{
printf("%d --> %d\n", start, end);
}
else
{
hanoi(disks - 1, start, temp, end);
printf("%d --> %d\n", start, end);
hanoi(disks - 1, temp, end, start);
}
}
The C code is correct and prints:
1 --> 3
1 --> 2
3 --> 2
1 --> 3
2 --> 1
2 --> 3
1 --> 3
Solution 1:[1]
The initial call is:
hanoi(3, 1, 3, 2)
Thus the first recursive call is:
hanoi(3-1, 1, 2, 3)
and the second recursive call is:
hanoi(3-1-1, 1, 3, 2)
The last 3 lines of the hanoi() function are correct as they are now. Try to visualize it: To move D disks from "start" to "end":
- first move D-1 disks from "start" to "temp", then
- move the last (i.e. the largest) disk from "start" to "end", and finally
- move the D-1 disks from "temp" to "end"
This corresponds to the three lines of code.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | nielsen |
