Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
Example:
Input:
words = ["oath","pea","eat","rain"]
and board =
[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
Output:
["eat","oath"]
class Solution {
class Trie{
public:
Trie *children[26]; //指向其子序列 从'a'到'z'
bool leaf; //该结点是否是叶子结点
int idx; //如果该节点是叶子结点, idx是该单词在vector中的序号
Trie()
{
this->leaf = false;
this->idx = 0;
fill_n(this->children, 26, nullptr);
}
};
public:
void insertWords(Trie *root, vector<string>& words, int idx)
{
int pos = 0, len = words[idx].size();
while(pos < len)
{
if(NULL == root->children[words[idx][pos] - 'a'])
root->children[words[idx][pos] - 'a'] = new Trie();
root = root->children[words[idx][pos++] - 'a'];
}
root->leaf = true;
root->idx = idx;
}
Trie * buildTrie(vector<string>& words)
{
Trie * root = new Trie();
for(int i = 0; i < words.size(); ++i)
insertWords(root, words, i);
return root;
}
void checkWords(vector<vector<char>>& board, int i, int j, int row, int col, Trie *root, vector<string> &res, vector<string>& words)
{
if(i <0 || j < 0 || i >= row || j >= col)
return;
if(board[i][j] == 'X')
return;
if(NULL == root->children[board[i][j] - 'a'])
return;
char temp = board[i][j];
if(root->children[temp - 'a']->leaf)
{
res.push_back(words[root->children [temp - 'a']->idx]);
root->children[temp - 'a']->leaf = false;
}
board[i][j] = 'X';
checkWords(board, i-1, j, row, col, root->children[temp-'a'], res, words);
checkWords(board, i+1, j, row, col, root->children[temp-'a'], res, words);
checkWords(board, i, j-1, row, col, root->children[temp-'a'], res, words);
checkWords(board, i, j+1, row, col, root->children[temp-'a'], res, words);
board[i][j] = temp;
}
vector<string> findWords(vector<vector<char>>& board, vector<string>& words)
{
vector<string> res;
int row = board.size();
if(0==row)
return res;
int col = board[0].size();
if(0==col)
return res;
int wordCount = words.size();
if(0==wordCount)
return res;
Trie *root = buildTrie(words);
int i,j;
for(i =0 ; i<row; i++)
{
for(j=0; j<col && wordCount > res.size(); j++)
{
checkWords(board, i, j, row, col, root, res, words);
}
}
return res;
}
};