Domain: Algorithms & Data Structures

## Problem

You are given an `n × m` grid (`1 ≤ n,m ≤ 200`) filled with digits `0..9`.

For each digit `d` (`0..9`), you are also given a move vector `(a[d], b[d])` (each component in `[-200,200]`).

Define Wilbur’s movement rule:

- If Wilbur is currently at cell `(x,y)` and the digit there is `d`, then his **forced next position** is `(x + a[d], y + b[d])` **if** that cell is inside the grid.
- If the forced next position is outside the grid, Wilbur **stays** at `(x,y)`.

Before each forced move, Wilbur may either:
- append the current cell’s digit to a whiteboard string, or
- append nothing.

Digits appended over time form a string (appended to the end each time).

You are given `q` query strings `s1..sq` (digits only). For each query `s`, determine whether there exists **some starting cell** such that, after finitely many forced moves (and optional writes), Wilbur can obtain **exactly** the string `s` on the whiteboard.

### Input
- `n m q` (`1..200`)
- `n` lines of `m` digits each (the grid)
- 10 lines: for digit `d`, line contains `a[d] b[d]`
- `q` lines: the query strings (total length over all queries ≤ `1,000,000`)

### Output
For each query, print `YES` if possible, else `NO`.


Grading rubric:
criterion: The answer models the forced movement as a directed graph on the grid cells in which every vertex has outdegree exactly 1.
weight: 10
criterion: The answer states that when the forced next position is outside the grid, the transition is a self-loop (the cell transitions to itself).
weight: 10
criterion: The answer states that any writable whiteboard string is a subsequence of the digit sequence along the forced walk from a chosen start cell.
weight: 10
criterion: The answer states that each (weakly) connected component of a functional graph contains exactly one directed cycle.
weight: 10
criterion: The answer defines the reverse adjacency relation in the form rev[u] = { v : to[v] = u}?
weight: 10
criterion: The answer states that the query string is reversed (r = reverse(s)) for the main search procedure.
weight: 10
criterion: The answer defines a per-query transition nxt(pos, d) that advances the matched position by 1 exactly when r[pos] equals digit d.
weight: 10
criterion: The answer defines bestPos[v] as the maximum matched-prefix length reached so far at vertex v.
weight: 10
criterion: The answer includes a dominance pruning rule that discards a visit to vertex v when the new matched length is less than or equal to bestPos[v].
weight: 10
criterion: The answer includes an explicit acceptance condition that outputs YES when the matched length reaches L.
weight: 10

Answer:
### 1) Build the functional graph of forced moves

Index each cell `(x,y)` as a vertex `v` (total `V = n*m ≤ 40000`).  
Let `dig[v]` be its digit.

Compute the forced transition `to[v]`:
- Let `d = dig[v]`.
- Candidate `(nx, ny) = (x + a[d], y + b[d])`.
- If inside the grid: `to[v] = id(nx,ny)`, else `to[v] = v` (self-loop).

So the directed graph is **functional**: every vertex has outdegree exactly 1.  
Hence each weakly connected component contains exactly one directed cycle, with directed trees feeding into it.

We will also build the reverse adjacency list:
\[
rev[u] = \{ v \mid to[v] = u \}.
\]

---

### 2) Convert the “write some visited digits” condition to a subsequence problem

Fix a starting vertex `start`. The forced movement generates an infinite walk:
\[
start, to[start], to[to[start]], \dots
\]
Wilbur can choose to write or skip at each visited vertex, so the produced string is **exactly a subsequence** of the digit sequence along this walk (and he may stop after finishing the string).

So for each query string `s`, we need to know whether there exists a start vertex whose walk contains `s` as a subsequence.

---

### 3) Reverse the query and run the process on the reversed graph

Let `s` be a query, length `L`, and let `r = reverse(s)`.

Instead of searching forward for `s` as a subsequence along `to[]`, we search for `r` as a subsequence along a walk in the **reversed graph** that starts on a cycle and moves outward:
- Reversing time turns “following `to[]`” into “choosing a predecessor from `rev[]`”.
- Cycles remain cycles after reversing edges.
- In the reversed functional graph, every component is a directed cycle with directed trees **going out of** the cycle.

Thus any reversed-time walk can:
1) loop around the cycle any number of steps (including 0),
2) then move outward along tree edges (cannot return to the cycle).

This matches the idea that forward-time walks eventually enter a cycle and then repeat it forever.

---

### 4) Precompute subsequence “next-state” table for the reversed string

For each query string `r` (length `L`), build:
- `nxt[pos][d]` for `pos = 0..L` and digit `d ∈ {0..9}`

Interpretation:
- `nxt[pos][d]` = the new position after greedily consuming digit `d` starting from `pos`:
  - if `pos < L` and `r[pos] == d`, then `nxt[pos][d] = pos+1`
  - else `nxt[pos][d] = pos`

(Equivalently, since we only need single-character consume/skip, this is just a constant-time transition.)

So consuming along any digit sequence becomes repeated application of `pos = nxt[pos][digit]`.

---

### 5) DFS with dominance pruning from cycles in the reversed graph

For a fixed query, we perform a reachability-style DP over states `(v, pos)`:
- `v` is a vertex,
- `pos` is how many characters of `r` have been matched so far.

We maintain an array `bestPos[v]` initialized to `-1`.
Meaning: we have already reached vertex `v` with some matched prefix length `bestPos[v]`, and any future arrival with `pos ≤ bestPos[v]` is useless (it cannot lead to matching more of `r` than what we already could from `v`).

DFS routine `dfs(v, pos)`:
1) If `pos == L`, we can stop: answer is `YES`.
2) Let `pos2 = nxt[pos][dig[v]]` (choose to write if it matches next, else effectively skip).
3) If `pos2 <= bestPos[v]`, return (dominated).
4) Set `bestPos[v] = pos2`.
5) For each predecessor `u` in `rev[v]`, call `dfs(u, pos2)`.

We must allow starting points that can loop on cycles to gain matches before leaving.
To handle looping, for each directed cycle we do:
- pick any cycle vertex as root,
- traverse the cycle edges in order and repeatedly relax `bestPos` on cycle vertices until no improvement occurs (at most `L` improvements total across the cycle because `bestPos` increases and is bounded by `L`),
- from the cycle vertices, launch `dfs` into outgoing tree edges (their `rev[]` children not on the cycle).

If any DFS reaches `pos == L`, print `YES`; otherwise `NO`.

Because `Σ = 10` and the graph size is at most `40000`, this pruning-based DFS runs fast in practice, and the total work is bounded by `O(V * Σ + L)` per query under the functional-graph structure and the monotonic `bestPos` pruning.

---

### 6) Output

Run the above per query string and print `YES` / `NO`.