Problem:
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"]
.
Analysis:
Solutions:
C++:
class TrieNode {
public:
// Initialize your data structure here.
TrieNode() {
mp_node.resize(26, NULL);
mb_is_word = false;
}
vector<TrieNode *> mp_node;
bool mb_is_word;
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
void insert(string s) {
TrieNode *p_curr = root;
for(int i = 0; i < s.size(); ++i) {
if(p_curr->mp_node[s[i] - 'a'] == NULL)
p_curr->mp_node[s[i] - 'a'] = new TrieNode();
p_curr = p_curr->mp_node[s[i] - 'a'];
}
p_curr->mb_is_word = true;
}
// Returns if the word is in the trie.
bool search(string key) {
TrieNode *p_curr = root;
for(int i = 0; i < key.size(); ++i) {
if(p_curr->mp_node[key[i] - 'a'] == NULL)
return false;
p_curr = p_curr->mp_node[key[i] - 'a'];
}
return (p_curr->mb_is_word ? true : false);
}
// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix) {
TrieNode *p_curr = root;
for(int i = 0; i < prefix.size(); ++i) {
if(p_curr->mp_node[prefix[i] - 'a'] == NULL)
return false;
p_curr = p_curr->mp_node[prefix[i] - 'a'];
}
return true;
}
private:
TrieNode* root;
};
void dfs(vector<vector<char> >& board, vector<vector<bool> >& visited, string str, int x, int y, vector<string>& found, Trie& trie)
{
if(x < 0 || x >= board.size() || y < 0 || y >= board[0].size() || visited[x][y])
return;
str.push_back(board[x][y]);
if(!trie.startsWith(str))
return;
if(trie.search(str) && find(found.begin(), found.end(), str) == found.end())
found.push_back(str);
visited[x][y] = true;
dfs(board, visited, str, x - 1, y, found, trie);
dfs(board, visited, str, x, y - 1, found, trie);
dfs(board, visited, str, x + 1, y, found, trie);
dfs(board, visited, str, x, y + 1, found, trie);
visited[x][y] = false;
}
vector<string> findWords(vector<vector<char> >& board, vector<string>& words) {
vector<string> found;
if(board.empty() || words.empty())
return found;
Trie trie;
for(int i = 0; i < words.size(); ++i)
trie.insert(words[i]);
int row = board.size();
int col = board[0].size();
vector<vector<bool> > visited(row, vector<bool>(col, false));
for(int i = 0; i < board.size(); ++i) {
for(int j = 0; j < board[0].size(); ++j)
dfs(board, visited, "", i, j, found, trie);
}
return found;
}
Java
:
Python: