### Max Words Package

You are given a NxN matrix composed of lowercase letters and a list of words. Your task is to find out the largest list of words that can be formed by the letters in the matrix.

Constraints:

• each letter can only be used once for a word;
• once the cell (letter) in the matrix is taken by a word, then the other words in the same list cannot use that cell again.

Example:
Input:
{
{‘o’, ‘a’, ‘a’, ‘n’},
{‘e’, ‘t’, ‘a’, ‘e’},
{‘i’, ‘h’, ‘k’, ‘r’},
{‘i’, ‘f’, ‘l’, ‘v’}
}
{“eat”, “oath”, “aak”, “ner”, “oei”, “thfl”}
Output:
{“oei”, “ner”, “aak”, “thfl”}
Explanation:
Actually all these words can be formed in the matrix, but we have to ensure the biggest list of words.

• if we take “eat”, then the list should be {“eat”, “oei”};
• if we take “oath”, then the list should be {“oath”, “aak”, “ner”};
• if we take “aak”, then the list should be {“oei”, “aak”, “ner”, “thfl”};
So we should return the biggest list {“oei”, “aak”, “ner”, “thfl”} as the final result.

### Solution

Clearly since there are lots of words we need to search in the matrix, we should take advantage of the Trie Tree to avoid redundant checking for words with the same prefix. So let’s just hit the road:

• build the Trie Tree based on the list of the words provided;
• start the search from each possible cell in the matrix and do backtracking: as soon as we take that cell, we label it and after the further searching, we un-label it for other searching paths;
There will be two directions in the searching:
1. if the current node indicate a complete word then we collect the word and try to start another word searching from the root of the TreeTrie again and try each possible unlabelled cell; and in each try, we collect the bigger valid result to update the current container;
2. if the current node does not indicate a word, then we try the other four different directions around the current cell and also collect the valid results and update the current container.

Note the corner cases:

1. out of range
2. labelled cell
3. invalid node

Always welcome new ideas and `practical` tricks, just leave them in the comments!