HANOI tower (Application of divide and conquer Law)

Source: Internet
Author: User

1. Divide and conquer Law

The design idea of the division and control law is to break down a big problem that is hard to solve directly into the same problems of small scale, so as to break through and conquer each other separately.

Generally, the splitting algorithm has three steps on each layer of recursion:

(1) decomposition: the problem is broken down into a series of subproblems.

(2) solving: recursively solving each subproblem. If the sub-problem is small enough, solve it directly.

(3) Merge: Merge the subproblem into the original problem.

2. Hanoi Tower

Typical application of divide and conquer law:

When there is only one plate, you can directly move from A to C;

If we know the n-1 Plate moving scheme, the N Plate moving scheme is as follows:

First, move n-1-1 plates from A to B with the help of C, and then directly move the n-th plate from A to C, then, the n-1 plates at B are moved from B to C with. Now, all the dishes are moved.

Void Hanoi (int n, char a, char B, char c) // move n plates from A to C through B

{

If (n> 1 ){

Hanoi (n-1, A, C, B); // first move the first n-1 plates from A to B

Move (n, a, c); // move the nth plate from A to C.

Hanoi (n-1, B, A, C); // move the n-1-1 plate from B to C through

} Else {

Move (n, a, c); // when there is only one plate, move directly from A to C. Recursive exit

}

}

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.