Word in the Letter Grid
You are given a grid of r rows and c columns. Every cell holds a lowercase English letter.
A word is found in the grid if you can pick a sequence of cells, one cell per letter of the word, such that:
- the letter in the
i-th chosen cell equals thei-th letter of the word; - every two consecutive chosen cells share a side (up, down, left or right; diagonal steps are not allowed);
- no cell is chosen more than once.
For each of q words, decide whether it is found in the grid.
Input
The first line contains two integers r and c (1 ≤ r, c and r·c ≤ 36).
Each of the next r lines contains a string of exactly c lowercase English letters: the rows of
the grid, from top to bottom.
The next line contains an integer q (1 ≤ q ≤ 50).
Each of the next q lines contains a word: a string of between 1 and 15 lowercase English letters.
Output
Print q lines. The i-th line must be YES if the i-th word is found in the grid and NO
otherwise.
Notes
In the first example, abcced is traced along the top row (a, b, c), down to the c in the
middle row, down to the e in the bottom row and left to d. The word abcb would need the only
b twice. adfb starts at the bottom-left a, steps right to d, up to f and up again to b.
In the second example, abab would have to step back onto the a and b it just used, so it is
not found, while aabbc uses five different cells. The grid has only two as, so aaa is not
found either.