Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
word-search-ii.cpp 2.86 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2016-03-09 23:30 +08:00 . Update word-search-ii.cpp
// Time: O(m * n * h), h is height of trie
// Space: O(26^h)
class Solution {
private:
struct TrieNode {
bool isString = false;
unordered_map<char, TrieNode *> leaves;
bool Insert(const string& s) {
auto* p = this;
for (const auto& c : s) {
if (p->leaves.find(c) == p->leaves.cend()) {
p->leaves[c] = new TrieNode;
}
p = p->leaves[c];
}
// s already existed in this trie.
if (p->isString) {
return false;
} else {
p->isString = true;
return true;
}
}
~TrieNode() {
for (auto& kv : leaves) {
if (kv.second) {
delete kv.second;
}
}
}
};
public:
/**
* @param board: A list of lists of character
* @param words: A list of string
* @return: A list of string
*/
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
unordered_set<string> ret;
vector<vector<bool>> visited(board.size(), vector<bool>(board[0].size(), false));
string cur;
TrieNode trie;
for (const auto& word : words) {
trie.Insert(word);
}
for (int i = 0; i < board.size(); ++i) {
for (int j = 0; j < board[0].size(); ++j) {
findWordsDFS(board, visited, &trie, i, j, cur, ret);
}
}
return vector<string>(ret.begin(), ret.end());
}
void findWordsDFS(vector<vector<char>> &grid,
vector<vector<bool>> &visited,
TrieNode *trie,
int i,
int j,
string cur,
unordered_set<string> &ret) {
// Invalid state.
if (!trie || i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size()) {
return;
}
// Not in trie or visited.
if (!trie->leaves[grid[i][j] ] || visited[i][j]) {
return;
}
// Get next trie nodes.
TrieNode *nextNode = trie->leaves[grid[i][j]];
// Update current string.
cur.push_back(grid[i][j]);
// Find the string, add to the answers.
if (nextNode->isString) {
ret.insert(cur);
}
// Marked as visited.
visited[i][j] = true;
// Try each direction.
const vector<pair<int, int>> directions{{0, -1}, {0, 1},
{-1, 0}, {1, 0}};
for (const auto& d : directions) {
findWordsDFS(grid, visited, nextNode,
i + d.first, j + d.second, cur, ret);
}
visited[i][j] = false;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助