169. Tower of Hanoi

169. Tower of Hanoi
 

The Tower of Hanoi problem (also known as the Tower of Hanoi problem) is a well-known problem. On the three pillars A, B, and C, there are n discs of different sizes (assuming the radius is 1-n respectively), and they are all stacked on top of mine A (as shown in the picture). Your goal is Move all the plates from Tower A to Tower C within the minimum number of legal moving steps.
The rules of each step in the game are as follows:

    Only one plate is allowed to move at each step (from the top of one column to the top of another column). During the
    movement, you must ensure that the large plate cannot be placed on top of the small plate (the small can be placed on top of the large, and the largest There cannot be any other size plates under the plate)

Icon:

void f(int n,string from,string to,vector<string>&vec)
    {
        
        if(n==1)
        {
            vec.push_back("from " + from + " to "+ to );
            return;
        }
        map<string,string>t;
        t["A"]="A";
        t["B"]="B";
        t["C"]="C";
        t.erase(from);
        t.erase(to);
        map<string, string>::iterator iter=t.begin();
        string tmp = iter->first;
      
        
        f(n-1,from,tmp,vec);
        f(1,from,to,vec);
        f(n-1,tmp,to,vec);
    }
     
     
    vector<string> towerOfHanoi(int n) {
        // write your code here
         vector<string> ret;
         f(n,"A","C",ret);
         
         return ret;
    }

Guess you like

Origin blog.csdn.net/yinhua405/article/details/112647177