TopCoder problem "HanoiTower" used in SRM 446 (Division II Level Three)



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.

 

Definition

    
Class:HanoiTower
Method:moves
Parameters:String, String, String
Returns:int
Method signature:int moves(String pegA, String pegB, String pegC)
(be sure your method is public)
    
 

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)
    
"CBACBACBAA"
""
""
Returns: 19

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=10573

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=13900&pm=10573

Writer:

crazyb0y

Testers:

PabloGilberto , ivan_metelsky , Chmel_Tolstiy , MThorn

Problem categories:

Brute Force, Search