212. Word Search II

Description

image-20210821225834663

image-20210821225848576

Solution

A classic usage of Trie Tree(prefix tree).

image-20210821225945053

Template:

1
2
3
4
5
6
7
8
9
class Trie{
Trie *next[26];
bool isEnd;
Trie(){
for(int i = 0; i< 26; i++)
next[i] = nullptr;
isEnd = false;
}
};

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class Trie{
public:
Trie* next[26];
bool isEnd;
Trie(){
for(int i = 0; i < 26; i++)
next[i] = nullptr;
isEnd = false;
}
};

class Solution {
vector<string> res;
vector<int> dir = {-1, 0, 1, 0, -1};
public:
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
Trie *root = new Trie();
for(auto word: words){
buildTree(root, word);
}
for(int i = 0; i < board.size(); i++){
for(int j = 0; j < board[0].size();j++){
string cur = "";
dfs(board,i,j,root, cur);
}
}
return res;
}

void dfs(vector<vector<char>>& board, int r, int c, Trie* root, string& curStr){
if(!root->next[board[r][c]-'a'])
return;
Trie *cur = root->next[board[r][c]-'a'];
curStr += board[r][c];
board[r][c] = '#';
if(cur->isEnd){
res.push_back(curStr);
cur->isEnd = false;
}
for(int i = 0; i < 4; i++){
int x = r + dir[i], y = c + dir[i+1];
if(x < 0 || x >= board.size() || y < 0 || y >= board[0].size() || board[x][y] == '#')
continue;
dfs(board,x,y,cur,curStr);
}
board[r][c] = curStr.back();
curStr.pop_back();
}

void buildTree(Trie *root, string word){
Trie *cur = root;
for(int i = 0; i < word.size(); i++){
char c = word[i];
if(!cur->next[c-'a']){
cur->next[c-'a'] = new Trie();
}
cur = cur->next[c-'a'];
if(i == word.size()-1)
cur->isEnd = true;
}
}
};

image-20210821230155334