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
.
做完Word Search點下面的鏈接跳到212...大量要查找的單詞,提示用trie樹.網(wǎng)上果然都是用trie樹的....不過只需要用到信息能剪枝就好啦就沒建立一個真正的trie樹.
struct Layer{
int close=0;//>0代表一個完整的詞且代表在words里的索引+1
array<Layer*,26> next{};//26個字母,不為0即代表當(dāng)前找到的是前綴或完整詞
~Layer(){
for(Layer*l:next)
delete l;
}
};
void find(vector<vector<char>>& board,int i,int j ,vector<string>& words,Layer*lay,vector<string>&res)
{
char cur=board[i][j];
if(cur=='-')return;
lay=lay->next[cur-'a'];
if(!lay)return;
if(lay->close){
res.push_back(words[lay->close-1]);
lay->close=0;
}
board[i][j]='-';//依然寫入其它字符防止重復(fù)使用
if(i+1<board.size())find(board,i+1,j,words,lay,res);
if(i>0)find(board,i-1,j,words,lay,res);
if(j+1<board[0].size())find(board,i,j+1,words,lay,res);
if(j>0)find(board,i,j-1,words,lay,res);
board[i][j]=cur;
}
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
Layer root;
for(int i=0;i<words.size();++i)
{
Layer*cur=&root;
for(char c:words[i]){
if(!cur->next[c-'a']){
cur->next[c-'a']=new Layer;
}
cur=cur->next[c-'a'];
}
cur->close=i+1;
}
vector<string> res;
for(int i=0;i<board.size();++i)
for(int j=0;j<board[0].size();++j)
{
find(board,i,j,words,&root,res);
}
return res;
}