本题源自leetcode 212
-----------------------------------------------------------------------
思路:
构造一个Trie单词查找树。然后用递归遍历棋盘。找到所有的单词。
代码:
class Trie{
public:
int idx;
bool leaf;
Trie* children[26];
Trie(){
this->idx = 0; //如果当前节点是结尾,idx 是这个字符串在字典中的下标
this->leaf = false; //表示是否是一个字符串的结尾
fill_n(this->children,26,nullptr); //指向其从a-z的开始子串的指针。
}
};
public:
void insertWords(Trie* root,vector<string>& words,int idx){
int len = words[idx].size();
int i = 0;
while(i < len){
if(root->children[words[idx][i] - 'a'] == NULL)
root->children[words[idx][i] - 'a'] = new Trie();
root = root->children[words[idx][i] - 'a'];
i++;
}
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;
}
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
vector<string> res;
int row = board.size();
if(row == 0)
return res;
int col = board[0].size();
if(col == 0)
return res;
int n = words.size();
if(n == 0)
return res;
Trie* root = buildTrie(words);
for(int i = 0; i < row; i++){
for(int j = 0; j < col && n > res.size(); j++){
dfs(board,words,res,root,i,j,row,col);
}
}
return res;
}
void dfs(vector<vector<char>>& board,vector<string>& words,vector<string>& res,Trie* root,int i,int j,int row,int col){
if(board[i][j] == '#') //已经访问过
return;
char tmp = board[i][j];
if(root->children[tmp - 'a'] == NULL)
return ;
if(root->children[tmp - 'a']->leaf){
res.push_back(words[root->children[tmp - 'a']->idx]);
root->children[tmp - 'a']->leaf = false;
}
board[i][j] = '#';
if(i > 0)
dfs(board,words,res,root->children[tmp - 'a'],i-1,j,row,col);
if(i < row - 1)
dfs(board,words,res,root->children[tmp - 'a'],i+1,j,row,col);
if(j > 0)
dfs(board,words,res,root->children[tmp - 'a'],i,j-1,row,col);
if(j < col - 1)
dfs(board,words,res,root->children[tmp - 'a'],i,j+1,row,col);
board[i][j] = tmp;
}