#K92572. Forming a Word in a Wildcard Grid

    ID: 38227 Type: Default 1000ms 256MiB

Forming a Word in a Wildcard Grid

Forming a Word in a Wildcard Grid

You are given an \(n \times m\) grid where each cell contains an uppercase letter or a wildcard character ?. The wildcard can substitute for any uppercase letter. Your task is to determine whether it is possible to form a given target word by starting from some cell and moving consecutively to adjacent cells (up, down, left, or right) without revisiting any cell. When matching a letter, the cell's letter must either match the corresponding character in the target word or be a wildcard.

Note: Two cells are considered adjacent if they share a side. The usage of a cell is allowed only once in building the word.

Formally, let the grid be denoted as \(G\) of size \(n\) rows and \(m\) columns, and the target word be \(T = t_1t_2\ldots t_k\). Find if there exists a path \( (i_1,j_1), (i_2,j_2), \ldots, (i_k,j_k) \) such that:

  • \(G[i_l][j_l] = t_l\) or \(G[i_l][j_l] = \texttt{?}\) for all \(1 \le l \le k\),
  • Each consecutive cells are adjacent (i.e. \(|i_l - i_{l+1}| + |j_l - j_{l+1}| = 1\)),
  • All cells in the path are distinct.

Output YES if such a path exists, otherwise output NO.

inputFormat

The input is read from stdin and consists of:

  1. A line with two integers \(n\) and \(m\), representing the number of rows and columns of the grid.
  2. Next \(n\) lines, each containing a string of length \(m\) representing a row of the grid.
  3. A line containing the target word.

It is guaranteed that the grid contains only uppercase letters and the wildcard character ?.

outputFormat

Print a single line to stdout with YES if it is possible to form the target word by following the rules. Otherwise, print NO.

## sample
4 5
AB?F?
C?DGE
???GH
IJK?L
BDGFI
YES