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:
{“dog”, “dad”, “dgdg”, “can”, “again”}
return {“dog”, “dad”, “can”, “again”}
思路:利用给定的字典构建trie树,减少重复遍历,同时对给定的矩阵进行深度优先搜索,判断给定的字典中的字符串是否存在于矩阵中。
C++ 代码如下:
class TrieNode{
public:
TrieNode* child[26];
string str;
TrieNode(){
str = "";
memset(child, 0, sizeof(child));
}
};
class Solution {
public:
/**
* @param board: A list of lists of character
* @param words: A list of string
* @return: A list of string
*/
vector<string> results;
TrieNode* root;
void insert(TrieNode* p, string s){
for(int i=0; i<s.size(); ++i){
if(p->child[s[i]-'a']==0) p->child[s[i]-'a'] = new TrieNode();
p = p->child[s[i]-'a'];
}
p->str = s;
}
void search(vector<vector<char>> &board, vector<vector<bool>> &mask, TrieNode* p, int x, int y){
if(p->str != ""){
results.push_back(p->str);
p->str = "";
}
mask[x][y] = false;
int row = board.size(), col = board[0].size();
if(x+1<row && mask[x+1][y] && p->child[board[x+1][y]-'a']) search(board, mask, p->child[board[x+1][y]-'a'], x+1, y);
if(y+1<col && mask[x][y+1] && p->child[board[x][y+1]-'a']) search(board, mask, p->child[board[x][y+1]-'a'], x, y+1);
if(x-1>=0 && mask[x-1][y] && p->child[board[x-1][y]-'a']) search(board, mask, p->child[board[x-1][y]-'a'], x-1, y);
if(y-1>=0 && mask[x][y-1] && p->child[board[x][y-1]-'a']) search(board, mask, p->child[board[x][y-1]-'a'], x, y-1);
mask[x][y] = true;
}
vector<string> wordSearchII(vector<vector<char>> &board, vector<string> &words) {
// write your code here
if(board.size()==0) return results;
root = new TrieNode();
for(int i=0; i<words.size(); ++i) insert(root, words[i]);
vector<vector<bool> > mask(board.size(), vector<bool>(board[0].size(), true));
for(int i=0; i<board.size(); ++i)
for(int j=0; j<board[0].size(); ++j)
if(root->child[board[i][j]-'a']) search(board, mask, root->child[board[i][j]-'a'], i, j);
return results;
}
};