#K70482. Word Search in Grid

    ID: 33318 Type: Default 1000ms 256MiB

Word Search in Grid

Word Search in Grid

Given a grid of lowercase English letters with dimensions R and C, and a list of words, determine whether each word can be found in the grid.

You can start from any cell in the grid and form a word by moving in any of the eight possible directions (horizontally, vertically, or diagonally). Each cell can be used at most once when forming a single word. More formally, from a cell at position (i, j), you may move to any cell (i+dx, j+dy) where \(dx, dy \in \{-1, 0, 1\}\) and \((dx, dy) \neq (0, 0)\).

Your task is to output YES if a word can be found under these rules, and NO otherwise.

inputFormat

The input is provided via stdin and has the following format:

  1. The first line contains two space-separated integers: R (the number of rows) and C (the number of columns).
  2. The next R lines each contain a string of length C, representing the rows of the grid.
  3. The following line contains an integer N, denoting the number of words.
  4. The next N lines each contain a word to be searched in the grid.

outputFormat

For each word, print a line containing YES if the word can be found in the grid according to the movement rules, or NO if it cannot be found. The output should be written to stdout.

## sample
4 4
abcd
efgh
ijkl
mnop
3
abcf
ijkl
mnop
YES

YES YES

</p>