Pac-Man
Time limit1sMemory limit256 MB
Merge two Pac-Men that move in lockstep on a wrapping maze with walls and ghosts using the fewest joystick pushes.
- Level
Medium7 of 10
- Topics
- BFS, Graph, Shortest path
- Solved
- No attempts yet
Problem
Chungho was playing Pac-Man when one Pac-Man split into two. The two Pac-Men stand on different cells, but they answer the single joystick in the same way. Push north and both move one cell north. Push east and both move one cell east.
The maze is an grid. A Pac-Man whose destination cell holds a wall stays where it is. A Pac-Man that meets a ghost is eaten on the spot, so a direction is never used when it would send either of the two Pac-Men into a cell holding a ghost. The ghosts never move. A Pac-Man that leaves the maze on one side reappears on the opposite side.
The two Pac-Men do not block each other. They are merged when both stand on the same cell after a move, and passing through each other to swap places is not a merge.
Chungho wants to merge the two Pac-Men as fast as he can. Find the smallest number of moves and the directions he pushes, in order.
Input
The first line has the number of test cases ().
The first line of each test case has the number of rows and the number of columns (). Each of the next lines has the maze as characters. The characters mean:
Pis a Pac-ManXis a wallGis a ghost.is an empty cell
Every maze holds exactly two P characters, and the two Pac-Men stand on different cells.
Output
Print one line for each test case.
If the two Pac-Men can be merged, print the smallest number of moves, then one space, then the directions in order. North is N, east is E, south is S, and west is W. When several shortest sequences exist, print the one that comes first in lexicographic order, where the letters are ordered E, N, S, W.
If the two Pac-Men cannot be merged, print IMPOSSIBLE.