This page is still under construction.

Parts of this page are still being built. What you see may change.

Boggle

Interview

Time limit1sMemory limit256 MB

Summary
Find every dictionary word that can be spelled on each letter grid with adjacent cells and no cell reused, treating q as qu.
Level

Medium5 of 10

Topics
Backtracking, Trie, DFS
Solved
No attempts yet

Problem

Boggle is a game played with 16 dice that carry one letter on each face. The dice fill a 4x4 grid, and players look for words by joining letters on adjacent dice. In this problem you write a program that finds dictionary words in a letter grid the same way.

Inside a word, every letter must be adjacent to the previous letter in the grid, horizontally, vertically, or diagonally. One grid cell may be used at most once in a single word. The same letter may appear several times in a word when it comes from different cells.

In ordinary Boggle each face carries a single letter, with one exception. No face carries q by itself, and the two letters qu appear together instead. The grids here follow the same rule, so a cell holding q counts as the two letters qu.

Input

The first line contains the number of dictionary words WW (1≤W≤2001 \le W \le 200).

Each of the next WW lines contains one word made of 1 to 25 lowercase ASCII letters (a-z). All dictionary words are different.

The dictionary is followed by one or more letter grids. Each grid starts with a line holding its size DD (2≤D≤82 \le D \le 8), and the grid is a D×DD \times D square. The next DD lines each contain DD lowercase ASCII letters and give one row of the grid. A line holding 0 in place of DD ends the input.

Output

For each grid, print the following.

  1. Every dictionary word found in that grid, one per line, in alphabetical order.
  2. A line holding a single hyphen -.

Examples2

  1. Example 1

    Input
    3
    april
    purple
    quilt
    5
    rprit
    ahqln
    ietep
    zrysg
    ogwey
    3
    pel
    aup
    bcr
    0
    
    Expected output
    april
    quilt
    -
    purple
    -
    
  2. Example 2

    Input
    1
    ab
    2
    ab
    cd
    0
    
    Expected output
    ab
    -