Out of Sight

Time limit1sMemory limit128 MB

Problem

You fell asleep at your desk again and woke to the sound of newly installed security-camera robots rolling out into the office corridors. If any robot photographs you, you are in serious trouble. Fortunately, you can pull up on your computer the exact route each robot is programmed to follow, so you can plan your own moves to stay out of every robot's line of sight.

The robots move in discrete unit steps, each step going north, east, south, or west. On each step you may also move one unit north, east, south, or west (where a wall permits), or you may stay in place. You and every robot move at the same time, one step per turn.

Neither you nor any robot may move through a wall or leave the building.

Immediately after moving, every robot takes a photograph looking north, south, east, and west. You are captured if you stand on the same row or the same column as a robot with no wall between you and that robot. You are also captured if, at the end of a step, you are standing on the same cell as a robot.

Input

The input contains one or more mazes. Each maze starts with a line holding two integers $w$ and $h$: the width (west-to-east) and the height (north-to-south) of the maze. Neither you nor any robot may leave this rectangular area; it is treated as fully enclosed, although it may also contain interior walls. Input ends when $w < 3$ or $h < 3$.

The header is followed by $h$ lines describing the maze, each containing at least $w$ characters; only the first $w$ characters of each line are significant and any extra characters are ignored. Each character means:

  • a space denotes an open cell;
  • X denotes a wall;
  • Y denotes your starting cell and appears exactly once;
  • a single digit $k$ in the range $0$ to $9$ denotes the starting cell of robot $k$. No digit repeats, and a set of $N$ robots is labelled with the digits $0, 1, \ldots, N-1$.

The maze is followed by $N$ lines, one per robot; the $i$-th of these lines gives the moves of robot $i$. Each line contains from $0$ to $80$ characters, and all $N$ lines have the same length. Each character is one of N, S, E, W, meaning north, south, east, or west, where north points toward the first maze line and west points toward the first column. The characters list the robot's moves, one per turn.

Output

For each maze, print a single line:

You can hide for M turns.

where $M$ is the largest number of turns the robots can take while you remain unphotographed. If you can avoid detection for the entire programmed movement of the robots, $M$ equals the number of moves listed for each robot.