Data Structures C code 3.5: Tower of Hanoi problem

Abstract : The Tower of Hanoi problem is the dividing line of IQ.

1. Code

Code first, then nonsense.

#include <stdio.h>

/**
 * Hanoi.
 */
void hanoi(int paraN, char paraSource, char paraDestination, char paraTransit) {
	if (paraN <= 0) {
		return;
	} else {
		hanoi(paraN - 1, paraSource, paraTransit, paraDestination);
		printf("%c -> %c \r\n", paraSource, paraDestination);
		hanoi(paraN - 1, paraTransit, paraDestination, paraSource);
	}// Of if
}// Of hanoi

/**
 * Test the hanoi function.
 */
void hanoiTest() {
    printf("---- addToTest begins. ----\r\n");

	printf("2 plates\r\n");
	hanoi(2, 'A', 'B', 'C');

	printf("3 plates\r\n");
	hanoi(3, 'A', 'B', 'C');

    printf("---- addToTest ends. ----\r\n");
}// Of addToTest

/**
 The entrance.
 */
void main() {
	hanoiTest();
}// Of main

2. Running results

---- addToTest begins. ----
2 plates
A -> C
A -> B
C -> B
3 plates
A -> B
A -> C
B -> C
A -> B
C -> A
C -> B
A -> B
---- addToTest ends. ----
Press any key to continue

3. Code Description

  1. The recursive implementation of accumulation is purely for laying the foundation for this program.
  2. The Tower of Hanoi problem is very simple, and the function is fully calculated in only 9 lines; the Tower of Hanoi problem is very difficult, without figuring out a few parameters, it is directly dizzy in it.
  3. Here you can see the advantage of using meaningful, long variable names: program readability is greatly improved.
  4. The initial condition is 0 plates, so it is more convenient to judge the negative number of plates.
  5. The time complexity of the algorithm is O ( 2 n ) O(2^n)O(2n ), the space complexity isO ( n ) O(n)O ( n ) . All require drawing to explain.

Welcome to leave a message

Guess you like

Origin blog.csdn.net/minfanphd/article/details/124475686