您的位置:首页 > 其它

[LeetCode] Word Search II

2015-08-17 22:49 197 查看
A simple combination of Implement Trie (Prefix Tree) and Word Search. If you've solved them, this problem will become easy :-)

The following code is based on DFS and should be self-explanatory enough. Well, just go ahead and read it. It is long but clear :-)

class TrieNode {
public:
bool isKey;
TrieNode* children[26];
TrieNode() : isKey(false) {
memset(children, NULL, sizeof(TrieNode*) * 26);
}
};

class Trie {
public:
Trie() {
root = new TrieNode();
}

void add(string& word) {
TrieNode* run = root;
for (char c : word) {
if (!(run -> children[c - 'a']))
run -> children[c - 'a'] = new TrieNode();
run = run -> children[c - 'a'];
}
run -> isKey = true;
}

bool search(string& word) {
TrieNode* p = query(word);
return p && p -> isKey;
}

bool startsWith(string& prefix) {
return query(prefix) != NULL;
}
private:
TrieNode* root;
TrieNode* query(string& s) {
TrieNode* run = root;
for (char c : s) {
if (!(run -> children[c - 'a'])) return NULL;
run = run -> children[c - 'a'];
}
return run;
}
};

class Solution {
public:
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
Trie trie = Trie();
for (string word : words) trie.add(word);
int m = board.size(), n = board[0].size();
for (int r = 0; r < m; r++)
for (int c = 0; c < n; c++)
find(trie, board, "", r, c);
return vector<string> (st.begin(), st.end());
}
private:
unordered_set<string> st;
void find(Trie trie, vector<vector<char>>& board, string word, int r, int c) {
int m = board.size(), n = board[0].size();
if (board[r][c] == '%') return;
word += board[r][c];
if (!trie.startsWith(word)) return;
if (trie.search(word)) st.insert(word);
board[r][c] = '%';
if (r) find(trie, board, word, r - 1, c);
if (r < m - 1) find(trie, board, word, r + 1, c);
if (c) find(trie, board, word, r, c - 1);
if (c < n - 1) find(trie, board, word, r, c + 1);
board[r][c] = word.back();
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: