Leetcode212. 单词搜索 II
这道题需要用的前缀树,所以先做一道预备题:208. 实现 Trie (前缀树)
class Trie {
public:
struct Node {
bool is_end;
Node *son[26];
Node () {
is_end = false;
for (int i = 0; i < 26; i ++ )
son[i] = NULL;
}
}*root;
/** Initialize your data structure here. */
Trie() {
root = new Node();
}
/** Inserts a word into the trie. */
void insert(string word) {
auto p = root;
for (auto c : word) {
int u = c - 'a';
if (!p->son[u]) p->son[u] = new Node();
p = p->son[u];
}
p->is_end = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
auto p = root;
for (auto& c : word) {
int u = c - 'a';
if (!p->son[u]) return false;
p = p->son[u];
}
return p->is_end;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string word) {
auto p = root;
for (auto& c : word) {
int u = c - 'a';
if (!p->son[u]) return false;
p = p->son[u];
}
return true;
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/
思路:哈希+前缀树+回溯
class Solution {
public:
struct Node {
int id;
Node *son[26];
Node () {
id = -1;
for (int i = 0; i < 26; i ++ )
son[i] = NULL;
}
}*root;
vector<vector<char>> g;
unordered_set<int> ids;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
void insert(string& word, int id) {
auto p = root;
for (auto& c : word) {
int u = c - 'a';
if (!p->son[u]) p->son[u] = new Node();
p = p->son[u];
}
p->id = id;
}
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
g = board;
root = new Node();
for (int i = 0; i < words.size(); i ++ ) insert(words[i], i);
for (int i = 0; i < g.size(); i ++ )
for (int j = 0; j < g[0].size(); j ++ ) {
int u = g[i][j] - 'a';
if (root->son[u])
dfs(i, j, root->son[u]);
}
vector<string> res;
for (auto id : ids) res.push_back(words[id]);
return res;
}
void dfs(int x, int y, Node* p) {
if (p->id != -1) {
ids.insert(p->id);
}
char t = g[x][y];
g[x][y] = '.';
for (int i = 0; i < 4; i ++ ) {
int a = x + dx[i], b = y + dy[i];
if (a >= 0 && a < g.size() && b >= 0 && b < g[0].size() && g[a][b] != '.') {
int u = g[a][b] - 'a';
if (p->son[u]) dfs(a, b, p->son[u]);
}
}
g[x][y] = t;
}
};