problems / 148

Word in the Letter Grid

medium backtracking dfs strings 1000 ms · 256 MB

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 the i-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.

Example 1

Input

3 4
abce
sfcs
adee
4
abcced
see
abcb
adfb

Output

YES
YES
NO
YES

Example 2

Input

2 3
aab
ccb
4
abab
aabbc
ccbba
aaa

Output

NO
YES
YES
NO

Hints · reveal one at a time if you're stuck

Hint 1

Try a backtracking search: for each cell matching the first letter, walk through neighbouring cells that match the next letter. What must you do with a cell when a branch fails, so that other branches can still use it?

Hint 2

A plain search can wander through a huge number of paths before failing on a word like a long run of one letter followed by a missing one. Cheap checks come first: compare letter counts with the grid, and note that a word is found exactly when its reverse is, so search from the end whose letter is rarer.

report an issue Prefer your own editor? sooks prep 148 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.