OCAC summer second game Tower of Hanoi problem solution problem J

Tower of Hanoi
[Title] Description
Tower of Hanoi is a mathematical problem of an Indian legend formed: with three poles A, B, C, A has n pole disc perforations, the size of the disk successively smaller from the bottom to the top.
Requirements in accordance with the following rules will bar all discs moved to C:
      1. You can only move one disc
      2. The market can not be stacked in small cap above
to find out how many times the minimum need to move, move and print solutions.
[Input format
an integer n (1 <= n <= 15), the first bar A represents the number of disks.
[] Output format
of the first row, the number of outputting the least movement.
The following are printed once per line movement (e.g., movement of the uppermost disc to C A lever rod, the output "Move A to C").
[Input] Sample
3
[] sample output
. 7
the Move A to C
the Move A to B
the Move C to B
the Move A to C
the Move B to A
the Move B to C
the Move A to C
[Title] Analysis of
this question relates Algorithm: recursion.
We open a function dfs (char A, char B, char C, int n),
he represents: the n discs move from A to B via C.
So when 1:00 n ==, we direct output "Move A to C" on it.
When n> 1, we can think:
if I want the largest disc move from A to C, the other first we need the n-1 disks from A (via C) moves to B, then output "move a to C", and then the n-1 disks in the B-B from the mobile (via a) to C.
So to achieve dfs (char A, char B, char C, int n) pseudo-code (pseudo-code that is not fully conform to the syntax of a language, but you can understand the grammar; it seemed as though Wang teacher is Huzhou However as it is able to understand Hangzhou) as follows:
DFS (a, B, C, n-):
    IF the then outputting n-== 0 "the Move" II.A "to" .C.
    the else:
        DFS (a, C, B ,. 1-n-)
        . output "the Move" II.A "to" .C
        DFS (B, A, C,. 1-n-)
codes are as follows:

#include <bits/stdc++.h>
using namespace std;

void output(char A, char B) {
    printf("Move %c to %c\n", A, B);
}

void mov(char A, char B, char C, int n) { // A¾­¹ýBÒƶ¯µ½C
    if (n == 1) output(A, C);
    else {
        mov(A, C, B, n-1);
        output(A, C);
        mov(B, A, C, n-1);
    }
}

int n, ans;

int main() {
    cin >> n;
    ans = 1;
    for (int i = 2; i <= n; i ++) ans = ans * 2 + 1;
    cout << ans << endl;
    mov('A', 'B', 'C', n);
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/ocac/p/11131671.html