# LintCode 132. Word Search II -- Trie

Description
Given a matrix of lower alphabets and a dictionary. Find all words in the dictionary that can be found in the matrix. A word can start from any position in the matrix and go left/right/up/down to the adjacent position.

Example
Given matrix:
doaf
agai
dcan
and dictionary:

C++ 代码如下：

class TrieNode{
public:
string str;
TrieNode* child[26];
TrieNode(){
str = "";
for(int i=0; i<26; ++i) child[i] = NULL;
}
void insert(string t, int pos=0)
{
if(pos==t.size())
{
str = t;
return;
}
int c = t[pos] - 'a';
if(child[c]==NULL) child[c] = new TrieNode();
child[c]->insert(t, pos+1);
}
};

class Solution {
public:
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
TrieNode* node = new TrieNode();
vector<string> res;
if(board.size()==0) return res;

for(int i=0; i<words.size(); ++i)
node->insert(words[i]);

for(int i=0; i<board.size(); ++i)
for(int j=0; j<board[i].size(); ++j)
search(node, board, i, j, res);
return res;
}
void search(TrieNode* node, vector<vector<char>> &board, int x, int y, vector<string>& res){
if(x<0 || y<0 || x>=board.size() || y>=board[0].size()) return;
char c = board[x][y];
if(c-'a'<0) return;
TrieNode* cur = node->child[c-'a'];
if(cur==NULL) return;

if(cur->str != "")
{
res.push_back(cur->str);
cur->str = "";
}

board[x][y] = '#';
search(cur, board, x+1, y, res);
search(cur, board, x-1, y, res);
search(cur, board, x, y+1, res);
search(cur, board, x, y-1, res);
board[x][y] = c;

}
};

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120