This page is still under construction.

Parts of this page are still being built. What you see may change.

Bacteria

Interview

Time limit1sMemory limit128 MB

Summary
Simulate K bacteria moving on a grid, each turning by a digit read from its own matrix, and report when all share the trap cell.
Level

Medium6 of 10

Topics
Simulation, Implementation, Array, Math
Solved
No attempts yet

Problem

There is an experiment board divided into NN rows and MM columns. The topmost row is row 11 and the bottom row is row NN; the leftmost column is column 11 and the rightmost column is column MM.

KK intelligent bacteria are placed on the board. Each bacterium starts on an assigned cell and faces one of four directions: up, down, left, or right. Every second, each bacterium performs the following steps once, in order:

  1. Read the number XX written on its current cell. This number differs from bacterium to bacterium, and each bacterium reads the number that belongs to it.
  2. Rotate clockwise by 90∘90^\circ, XX times.
  3. If the cell it now faces lies outside the board, rotate 180∘180^\circ.
  4. Move one cell forward in the direction it faces.

One cell of the board holds a trap. Call the initial placement of the bacteria second 11. At the start of every second, the positions of all bacteria are checked first. If all bacteria are on the trap cell together, they are immediately caught and die, and that second is the answer. Otherwise every bacterium performs steps 11-44 once simultaneously, and time advances to the next second.

Write a program that finds, in seconds, when all bacteria die.

Input

The first line contains NN, MM, and KK. (3≤N,M≤503 \le N, M \le 50, 1≤K≤51 \le K \le 5)

The second line contains the row and column of the trap cell.

Then the descriptions of bacteria 11 through KK follow in order. Each description has two parts:

  • One line with the starting cell's row XiX_i, column YiY_i, and facing direction CiC_i. CiC_i is one of up U, right R, down D, or left L.
  • The next NN lines give an N×MN \times M matrix. Each element is a digit from 00 to 99 and denotes the number XX that bacterium ii reads when it is on cell (x,y)(x, y).

Output

Print, on the first line, the second at which all bacteria die. If the bacteria never all die, print −1-1.

Examples3

  1. Example 1

    Input
    3 3 1
    2 2
    1 1 R
    010
    000
    000
    
    Expected output
    3
    
  2. Example 2

    Input
    3 4 2
    2 2
    3 4 R
    2327
    6009
    2112
    3 2 R
    1310
    2101
    1301
    
    Expected output
    8
    
  3. Example 3

    Input
    4 4 3
    4 3
    1 1 U
    1001
    0240
    3322
    2327
    1 3 L
    9521
    2390
    3020
    2421
    2 2 D
    3397
    2013
    1102
    7302
    
    Expected output
    296