An advertising company produces commercials featuring ancient heroes such as Prometheus, Achilles, and Odysseus. To show how hard life was for these heroes, it runs computer simulations of their most famous ordeals. In this problem we simulate the ordeal of Theseus.
Theseus was an Athenian hero who slew the Minotaur, the half-man, half-bull monster that lived in an inescapable Labyrinth. His real challenge was not killing the monster but finding the way out. Here we simulate that task under the following rules.
The input consists of several labyrinth descriptions. Each description is given as follows.
# (rock), . (free space), or one of the uppercase letters T (Theseus' position), M (Minotaur), and S (sword). Each of T, M, and S appears exactly once in the whole labyrinth, and all three of those cubes count as empty and may be walked through.The last labyrinth description is followed by a line containing a single 0, which terminates the input; no output is produced for it.
For each labyrinth, print the line
Theseus needs S steps.
where $S$ is the smallest number of steps needed to start at Theseus' position, reach the cube holding the sword, then reach the cube holding the Minotaur, and finally return to Theseus' original position (where the exit is assumed to be). It is not possible to leave the labyrinth area; every cube outside the labyrinth counts as rock. The exit may lie in an interior cube and need not be on the "border".
If the situation cannot be solved at all, print
No solution. Poor Theseus!