HARD
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"].
Note:
You may assume that all inputs are consist of lowercase letters a-z.
click to show hint.
Hide Company Tags Airbnb
Hide Tags Backtracking Trie
Hide Similar Problems (M) Word Search
在第三遍leetcode开始,终于有点做题的感觉了。
Hint: TrieNode.
基本思想:把要搜索的word 都加进TrieTree, 遍历board 做dfs
很简单吧?但每一步都需要仔细斟酌。
比如题目要求:The same letter cell may not be used more than once in a word.
这就意味着我们要标记 current char under search 并且在search完要reset 它。
同时, 同样的word不能push 进我们的result两次!!这就意味着我们找到一个word就要改变它的isWord
flag.
除此之外, 在TrieNode class 的设计上,加了一个int indicates the current word’s position in words list.
code如下:
class TrieNode{
public:
TrieNode(){
isWord = false;
pos = 0;
for(int i = 0; i<26; ++i)
neighbors[i] = NULL;
}
bool isWord;
int pos;
TrieNode* neighbors[26];
};
class Solution {
public:
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
TrieNode* root = makeTrie(words);
int m = board.size(), n = board[0].size(), wordCnt = words.size();
vector<string> res;
for(int i = 0; i<m; ++i){
for(int j = 0; j<n && wordCnt > res.size(); ++j){// by using wordCnt> res.size() we can end the loop early.
searchDFS(board, i, j, root, res, words);
}
}
return res;
}
void searchDFS(vector<vector<char>>& board, int row, int col, TrieNode* node, vector<string>& res,vector<string>& words){
int m = board.size(), n = board[0].size();
if(row >= m || col >=n || row < 0 || col < 0 || board[row][col] == 'X'|| !node->neighbors[board[row][col] - 'a']) return;
char c = board[row][col];
if(node->neighbors[c - 'a']->isWord){
res.push_back(words[node->neighbors[c-'a']->pos]);
node->neighbors[c - 'a']->isWord = false;// avoid pushing duplicates.
}
board[row][col] = 'X';// mark current char is visited, every char can be used only once
vector<pair<int, int>> dir = {{row + 1, col}, {row - 1, col}, {row,col+1}, {row, col - 1}};
for(auto d : dir){
searchDFS(board, d.first, d.second, node->neighbors[c - 'a'], res, words);
}
board[row][col] = c;// recover current char
}
TrieNode* makeTrie(vector<string>& words){
TrieNode* root = new TrieNode();
for(int i = 0; i < words.size(); ++i){
TrieNode* p = root;
for(char c : words[i]){
if(!p->neighbors[c - 'a']) p->neighbors[c - 'a'] = new TrieNode();
p = p->neighbors[c - 'a'];
}
p->isWord = true;
p->pos = i;
}
return root;
}
};