原题链接https://leetcode.com/problems/word-search-ii/
Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
For example,
Given words = ["oath","pea","eat","rain"]
and board =
[ ['o','a','a','n'], ['e','t','a','e'], ['i','h','k','r'], ['i','f','l','v'] ]Return
["eat","oath"]
.
转载自http://blog.csdn.net/ljiabin/article/details/45846527
这道题一开始提示的就是使用前缀树,我居然想的是怎么把矩阵变成前缀树,觉得把他变成前缀树 不就相当于dfs了一次么,又占空间又费时间。
后来实在想不出来了,了去看了大牛的,发现结果是将words中的变成前缀树。天呐噜,居然是这样,然后瞬间觉得自己还是太年轻。以后想问题还是多方面的发散。
将words中的单词插入到前缀树中,然后dfs那个矩阵,如果没有以dfs得到的字符串为首的,直接返回。
//参考自http://blog.csdn.net/ljiabin/article/details/45846527
class TrieNode {
public:
// Initialize your data structure here.
TrieNode* next[26];
bool flag;
TrieNode() {
for (int i = 0; i < 26; ++i)
next[i] = NULL;
flag = false;
}
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
void insert(string& word) {
TrieNode* tmp = root;
for (auto &c : word)
{
if (tmp->next[c - 'a'] == NULL)
tmp->next[c - 'a'] = new TrieNode();
tmp = tmp->next[c - 'a'];
}
tmp->flag = true;
}
// Returns if the word is in the trie.
bool search(string& word) {
TrieNode* tmp = root;
for (auto &c : word)
{
if (tmp->next[c - 'a'] == NULL)
return false;
tmp = tmp->next[c - 'a'];
}
return tmp->flag;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string& prefix) {
TrieNode* tmp = root;
for (auto &c : prefix)
{
if (tmp->next[c - 'a'] == NULL)
return false;
tmp = tmp->next[c - 'a'];
}
return true;
}
private:
TrieNode* root;
};
class Solution {
public:
set<string> ans;
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
int n = board.size(), m = board[0].size();
Trie trie;
vector<vector<bool> >vis(n, vector<bool>(m));
if (board.empty() || words.empty())return vector<string>(ans.begin(), ans.end());
for (auto &s : words)
trie.insert(s);
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
dfs(board, vis, i, j, "", trie);
return vector<string>(ans.begin(), ans.end());
}
void dfs(vector<vector<char> >& board, vector<vector<bool> >& vis, int i, int j, string str, Trie& trie)
{
if (i < 0 || j < 0 || i >= board.size() || j >= board[0].size())return;
if (vis[i][j])return;
str += board[i][j];
if (!trie.startsWith(str))return;
if (trie.search(str))
ans.insert(str);
vis[i][j] = true;
dfs(board, vis, i + 1, j, str, trie);
dfs(board, vis, i - 1, j, str, trie);
dfs(board, vis, i, j + 1, str, trie);
dfs(board, vis, i, j - 1, str, trie);
vis[i][j] = false;
}
};