Coggle

Given a 5x5 letter grid and a dictionary, count how many dictionary words can be traced through adjacent cells without reusing a cell.

Medium6BacktrackingTrieDFSNo attempts yetTime limit1sMemory limit512 MB

Problem

Like everyone else on vacation, the cows play the cow version of the word game Boggle, called Coggle. In this game, 25 letter dice are rolled into a 5×55 \times 5 matrix like this one:

Z C C D X
K Q M N B
U O W Z Y
F C O I J
P A Q Z T

A word is made by starting at some letter and repeatedly moving to one of its (up to) eight neighbors, until the successive letters spell out a word from the dictionary. Cells that touch horizontally, vertically, or diagonally are neighbors. A word may not use the letter of the same die twice.

In the matrix above, the lower 'C' can be used to form the words "CAP", "COW", and "COOK", but not "COD" or "PACK". With the dictionary of the original problem, the complete list of words that can be formed in the matrix above is "CAP", "COOK", "COW", "OWN", "WIT", "WOO", "ZOO", and "ZOOM".

Help Bessie see how well she can do. Given five rows of five letters that represent the dice, and a dictionary, count how many words from the dictionary can be formed.

A word might be formed in more than one way. Such a word is still counted only once.

Input

Lines 1 to 5 describe the matrix. Line ii contains five space-separated uppercase letters that form row ii.

Line 6 contains NN, the number of words in the dictionary (1N<250001 \le N < 25\,000).

Each of the next NN lines contains one dictionary word. Every word is a string of 11 to 2020 uppercase letters, and all words are distinct.

Output

Print a single integer: the number of dictionary words that can be formed using the rules above.