Problem 635
Word Search II
Hard · 30 pts · Matrix, Trie, Backtracking
Problem
Given a board of lowercase letters and a list of distinct words, find every word that can be built from letters of sequentially adjacent cells, where adjacent means horizontally or vertically neighbouring and the same cell may not be used twice in one word. Print the found words in lexicographic order, or NONE if no word can be built. Put all words in a trie and run one backtracking search from every cell, following the trie, so that all words are searched together.
Input
The first line contains R and C. The next R lines are the rows of the board. Then a line with W, and a line with the W words.
Output
Print the found words in lexicographic order separated by spaces, or NONE.
Constraints
1 <= R, C <= 12; 1 <= W <= 30000; 1 <= |word| <= 10; words are distinct
Example input
4 4 oaan etae ihkr iflv 4 oath pea eat rain
Example output
eat oath
Explanation
On the board oaan / etae / ihkr / iflv, the word eat runs e → a → t and oath runs o → a → t → h through neighbouring cells. pea and rain cannot be formed, so the answer is eat oath.