Connection Status:
Competition Arena > HanoiTower
SRM 446 · 2009-08-08 · by crazyb0y · Brute Force, Search
Class Name: HanoiTower
Return Type: int
Method Name: moves
Arg Types: (string, string, string)
Problem Statement

Problem Statement

In this problem we consider a modification of the classical Hanoi Towers game. The rules of our modification are as follows:

  • There are three pegs: peg A, peg B and peg C.
  • Each peg initially contains zero or more discs.
  • All discs have the same size and there are three types of discs: type A, type B and type C.
  • In one move you can move a disc from the top of one peg onto the top of another peg.
  • Your goal is to have all discs of type A on peg A, all discs of type B on peg B and all discs of type C on peg C.
  • You must achieve your goal in the minimum possible number of moves.

The initial locations of the discs are given in the Strings pegA, pegB and pegC. Each character of pegA represents a disc located on peg A, where 'A' represents a disc of type A, 'B' represents a disc of type B and 'C' represents a disc of type C. The discs are given in order, from bottom to top. pegB and pegC describe the discs on pegs B and C, respectively, in the same format.

Return the minimum number of moves required to achieve the goal of the game.

Notes

  • It's always possible to achieve the goal of the game.

Constraints

  • pegA, pegB and pegC will contain only the characters 'A', 'B' and 'C'.
  • The total number of characters in pegA, pegB and pegC will be between 1 and 10, inclusive.
Examples
0)
"A"
"AA"
"AA"
Returns: 4

Move all discs of type A to peg A directly.

1)
"B"
"C"
"A"
Returns: 5

There is exactly one disc of each type in this example, so we will refer to each disc by its type. The following sequence of moves is the shortest: 1. Move disc A to peg A. 2. Move disc C to peg C. 3. Move disc A to peg C. 4. Move disc B to peg B. 5. Move disc A to peg A.

2)
"CBA"
""
""
Returns: 5

Again, there is exactly one disc of each type here, so we will refer to each disc by its type. The following sequence of moves is the shortest: 1. Move disc A to peg C. 2. Move disc B to peg B. 3. Move disc A to peg B. 4. Move disc C to peg C. 5. Move disc A to peg A.

3)
"BBBBBBBBBA"
""
""
Returns: 11

Move the disc of type A to peg C. Then move all discs of type B to peg B. Finally, move disc A back to peg A.

4)
"CCCCBBBAAA"
""
""
Returns: 16

Submissions are judged against all 68 archived test cases, of which 5 are shown here. Case numbers match the judge’s.

Coding Area

Language: C++17 · define a public class HanoiTower with a public method int moves(string pegA, string pegB, string pegC) · 68 test cases · 2 s / 256 MB per case

Submitting as anonymous