#C1876. Grid Navigation Challenge

    ID: 45129 Type: Default 1000ms 256MiB

Grid Navigation Challenge

Grid Navigation Challenge

You are given an n \(\times\) m grid of characters and a set of command sequences. For each sequence, start at the top-left corner of the grid, and follow the directional commands:

  • U: move up
  • D: move down
  • L: move left
  • R: move right

If a movement would move you outside the boundaries of the grid, ignore that move. After processing a full command sequence, output the character at the final position. The grid indices follow the standard programming convention where the top-left is at (0, 0).

Note: There may be multiple test cases given in one input. Each test case will be processed in order until a line containing -1 is encountered.

inputFormat

Input is read from standard input (stdin). Each test case begins with a line containing two integers (n) and (m) (the number of rows and columns of the grid). The next (n) lines each contain a string of length (m), representing the grid. This is followed by a line containing an integer (k), the number of command sequences. Then (k) lines follow, each containing a command sequence (a string comprised only of the characters U, D, L, R). The input terminates with a line containing -1.

outputFormat

For each command sequence in the input, output the resulting character on a new line in the order the sequences are processed.## sample

3 3
ABC
DEF
GHI
2
RRD
DDL
-1
F

G

</p>