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.
Example:
Input: board = [ ['o','a','a','n'], ['e','t','a','e'], ['i','h','k','r'], ['i','f','l','v'] ] words = ["oath","pea","eat","rain"] Output: ["eat","oath"]
Note:
- All inputs are consist of lowercase letters
a-z
. - The values of
words
are distinct.
分析
这一题可以简化成在Board中寻找单个word是否存在的问题。采用广搜的办法寻找是否存在该word。
但是题目中给了多个words,如果遍历words进行搜索,其实会比较浪费效率,因为每一个word都已经进行过广搜了。那么我们希望在依次搜索中能够找到所有的word。那么需要对words进行方便的存储和查找,可以使用TRIE树存储所有的word。当搜索的过程中发现找到了一个单词,那么就记录下来,如果当前搜索的string不在TRIE树中,就直接return。为了不重复使用char,可以将搜索的路径标成'0'。
Code
class Solution {
public:
struct TreeNode
{
bool c[26];
bool isWord;
TreeNode* next[26];
TreeNode(): isWord(false)
{
for (int i = 0; i < 26; i ++)
{
c[i] = false;
next[i] = NULL;
}
}
void InsertWord(string word)
{
if (word.size() == 0)
{
isWord = true;
return;
}
int index = word[0] - 'a';
c[index] = true;
if (!next[index])
{
next[index] = new TreeNode();
}
next[index]->InsertWord(word.substr(1));
}
};
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
vector<string> res;
int length = words.size();
if (length == 0)
{
return res;
}
int row = board.size();
if (row == 0)
return res;
int col = board[0].size();
TreeNode* root = new TreeNode();
for (int i = 0; i < length; i ++)
{
root->InsertWord(words[i]);
}
for (int i = 0; i < row; i ++)
{
for (int j = 0; j < col; j ++)
{
string prefix;
helper(board, i, j, root, prefix, res);
}
}
return res;
}
void helper(vector<vector<char>>& board, int x, int y, TreeNode* node, string prefix, vector<string>& res)
{
if (!node)
return;
if (node->isWord)
{
res.push_back(prefix);
node->isWord = false;
}
if (x < 0 || y < 0 || x >= board.size() || y >= board[0].size() || board[x][y] == '0')
return;
int index = board[x][y] - 'a';
if ((node->c)[index] == false)
return;
prefix.push_back(board[x][y]);
board[x][y] = '0';
helper(board, x-1, y, (node->next)[index], prefix, res);
helper(board, x, y-1, (node->next)[index], prefix, res);
helper(board, x+1, y, (node->next)[index], prefix, res);
helper(board, x, y+1, (node->next)[index], prefix, res);
board[x][y] = index + 'a';
return;
}
};
运行效率
Runtime: 180 ms, faster than 42.71% of C++ online submissions for Word Search II.
Memory Usage: 86.1 MB, less than 24.39% of C++ online submissions forWord Search II.