Under construction

Still being built. Things may change

Word Puzzle 2

Time limit2sMemory limit128 MB

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

Medium6 of 10

Topics
DFS, Backtracking, Trie
Solved
No attempts yet

Problem

A puzzle is a 5 x 5 grid with one uppercase letter in each cell. The task is to find dictionary words in that grid.

A word is traced by starting at any cell and repeatedly stepping to one of the eight adjacent cells, reading the letters in the order the cells are visited. No cell may be visited more than once.

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

In the puzzle above CAP, COW and COOK can be traced, while COD and PACK cannot.

Given the puzzle and the dictionary, count the dictionary words that can be traced in the puzzle.

Input

The first five lines hold the 5 x 5 puzzle. Each line has five uppercase letters separated by spaces.

The sixth line holds the number of dictionary words NN. (1≤N≤200001 \le N \le 20000)

Each of the next NN lines holds one dictionary word. Every word is a string of 1 to 7 uppercase letters, and no word is given twice.

Output

Print on the first line how many dictionary words can be traced in the puzzle.

Examples2

  1. Example 1

    Input
    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
    18
    CAP
    COOK
    COW
    OWN
    WIT
    WOO
    ZOO
    ZOOM
    COD
    PACK
    QUICK
    ZONE
    BOY
    JOY
    CAB
    MAP
    NOW
    TOP
    
    Expected output
    8
    
  2. Example 2

    Input
    A B C D E
    F G H I J
    K L M N O
    P Q R S T
    U V W X Y
    12
    ABC
    AGM
    ABA
    EJO
    YXW
    AZ
    AFK
    ABCDEFG
    AGMSY
    MHCB
    OJE
    YY
    
    Expected output
    8