Recursive and non-recursive C and C ++ source code

Source: Internet
Author: User
Tower of Hanoi(Also called Hanoi) is an ancient legend of India.

Brama, the God of heaven and earth (similar to pangu in China), left three diamond rods in a temple, and the first was covered with 64 gold slices, the largest one is in the bottom, and the other is smaller than one, which is stacked in sequence. The monks in the temple place them one by one from this rod to another, the middle stick can be used as a help, but only one can be moved at a time, and the big one cannot be placed on the small one. The computation results are terrible (the number of rounds being moved) by 18446744073709551615. Even if they have used up their whole life, they won't be able to move the gold.


Algorithm introduction:
In fact, the algorithm is very simple. When the number of dishes is N, the number of moves should be 2 ^ n-1 (if you are interested, you can prove it yourself ). Later, an American scholar discovered an unexpected simple method, which would take two steps in turn. First, sort the three columns in the order of finished fonts, and place all the discs on column A in the order of size. Then, determine the column discharge sequence based on the number of disks: if n is an even number, a B C is arranged clockwise;
If n is an odd number, a c B is arranged clockwise.
(1) Move disc 1 from the current column to the next column clockwise, that is, when n is an even number, if disc 1 is in column A, move it to B; if disc 1 is in column B, move it to C; If disc 1 is in Column C, move it to.
(2) Move the disc that can be moved from the other two columns to the new column. That is, move the disc on the non-empty column to the empty column. When both columns are not empty, move the smaller disc. This step does not clearly define which disc to move. You may think there are multiple possibilities. Otherwise, the actions that can be implemented are unique.
(3) perform (1) (2) Operations repeatedly, and finally move the tower as required.

Therefore, the result is very simple, that is, to move the gold tablet in one direction according to the mobile rule:
For example, a → C, A → B, C → B, A → C, B → A, B → A, B → C, A → C

The tower of Hanoi Problem is also a classic recursive problem in programming. Below we will provide different implementation source code for recursion and non-recursion.

Recursive Implementation of the tower of Hanoi algorithm C ++ source code

# Include <fstream> # include <iostream> using namespace STD; ofstream fout(“out.txt "); void move (int n, char X, char y) {fout <"move" <n <"number from" <x <"move to" <Y <Endl;} void hannoi (int n, char A, char B, char c) {If (n = 1) Move (1, a, c); else {hannoi (n-1, A, C, B ); move (n, a, c); hannoi (n-1, B, A, c) ;}} int main () {fout <"The following is a solution to the layer-7 Tower: "<Endl; hannoi (7, 'A', 'B', 'C'); fout. close (); cout <"output finished!" <Endl; return 0 ;}

Recursive Implementation of the tower of Hanoi algorithm C source code:

# Include <stdio. h> void Hanoi (int n, char a, char B, char c) {If (n = 1) {printf ("Move disk % d from % C to % C/N", n, a, c);} else {Hanoi (n-1, A, C, B ); printf ("Move disk % d from % C to % C/N", n, a, c); Hanoi (n-1, B, A, c) ;}} main () {int N; printf ("enter the number n to solve the n-level tower issue:/N"); scanf ("% d", & N); Hanoi (n, 'A', 'B', 'C ');}

C ++ source code for non-Recursive Implementation of the tower algorithm

# Include <iostream> using namespace STD; // The maximum number of disks is 64 const int max = 64; // It is used to indicate the information of each column. struct st {int s [Max]; // the disk storage on the column, int top; // the top of the stack, used for the top disc char name; // The column name, which can be an int top () in A, B, and C // gets the top element of the stack {return s [Top];} int POP () // outbound stack {return s [top --];} void push (int x) // inbound stack {s [++ top] = x ;}}; long POW (int x, int y); // calculate x ^ yvoid creat (ST ta [], int N ); // set the initial value void hannuota (ST ta [], long max) for the structure array; // The main function of moving the tower int main (void) {int N; CIN> N; // enter the number of disks st ta [3]; // The information of the three columns is stored in the structure array creat (TA, N ); // set the initial value long max = POW (2, n)-1 for the structure array; // The number of animations should be 2 ^ n-1 hannuota (TA, max ); // main function system ("pause"); Return 0;} void creat (ST ta [], int N) {ta [0]. name = 'a'; TA [0]. top = n-1; // place all the disks in the ascending order of column A for (INT I = 0; I <n; I ++) ta [0]. s [I] = n-I; // Column B, C, there is no disc ta [1]. top = TA [2]. top = 0; For (INT I = 0; I <n; I ++) Ta [1]. s [I] = TA [2]. s [I] = 0; // if n is an even number, place a B c If (N % 2 = 0) {ta [1] clockwise. name = 'B'; TA [2]. name = 'C';} else // if n is an odd number, place a c B {ta [1] in clockwise order. name = 'C'; TA [2]. name = 'B' ;}} long POW (int x, int y) {long sum = 1; for (INT I = 0; I <Y; I ++) sum * = x; return sum;} void hannuota (ST ta [], long max) {int K = 0; // the cumulative number of moves int I = 0; int ch; while (k <max) {// move disc 1 from the current pillar to the next pillar clockwise. CH = TA [I % 3]. pop (); TA [(I + 1) % 3]. push (CH); cout <++ k <":" <"Move disk" <ch <"from" <ta [I % 3]. name <"to" <ta [(I + 1) % 3]. name <Endl; I ++; // move the disc that can be moved from the other two columns to the new column if (k <max ){
// Move the disc on the non-empty column to the empty column. When the two columns are empty, move the smaller disc if (TA [(I + 1) % 3]. top () = 0 | TA (I-1) % 3]. top ()> 0 & TA [(I + 1) % 3]. top ()> Ta [(I-1) % 3]. top () {CH = TA (I-1) % 3]. pop (); TA [(I + 1) % 3]. push (CH); cout <+ + k <":" <"Move disk" <ch <"from" <ta [(I-1) % 3]. name <"to" <ta [(I + 1) % 3]. name <Endl;} else {CH = TA [(I + 1) % 3]. pop (); TA (I-1) % 3]. push (CH); cout <+ + k <":" <"Move disk" <ch <"from" <ta [(I + 1) % 3]. name <"to" <ta [(I-1) % 3]. name <Endl ;}}}}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.