class TrieNode {
public:
bool is_end;
vector<TrieNode*> children = vector<TrieNode*>(26, nullptr);
TrieNode() {
is_end = false; }
};
class Solution {
public:
TrieNode* root = new TrieNode();
void insert(string word) {
TrieNode* p = root;
for(int ii = 0; ii < word.size(); ii++) {
if(!p->children[word[ii] - 'a']) p->children[word[ii] - 'a'] = new TrieNode();
p = p->children[word[ii] - 'a'];
}
p->is_end = true;
}
set<string> S;
int H, W;
vector<vector<char> > g_board;
bool visited[12][12] = {
false};
void dfs(string str, TrieNode* p, int y, int x) {
if(y < 0 || x < 0 || y >= H || x >= W || visited[y][x] || !p->children[g_board[y][x] - 'a']) return ;
p = p->children[g_board[y][x] - 'a'];
str += g_board[y][x];
if(p->is_end) S.insert(str);
visited[y][x] = true;
dfs(str, p, y-1, x);
dfs(str, p, y+1, x);
dfs(str, p, y, x-1);
dfs(str, p, y, x+1);
visited[y][x] = false;
}
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
for(auto &word : words) insert(word);
H = board.size(), W = board[0].size();
g_board = board;
for(int ii = 0; ii < H; ii++) {
for(int jj = 0; jj < W; jj++) {
dfs("", root, ii, jj);
}
}
vector<string> result(S.begin(), S.end());
return result;
}
};
【leetcode 前缀树(字典树) C++】212. Word Search II
猜你喜欢
转载自blog.csdn.net/m0_37454852/article/details/113757693
今日推荐
周排行