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"]
.
先建trie树,然后dfs就好
struct node
{
vector<node*> a;
bool word;
node()
{
word = false;
a.resize(26,NULL);
}
};
class Solution {
public:
node* root;
set<string> SET;
void insert(string word)
{
node* now = root;
for(int i=0;i<word.size();i++)
if(now->a[ word[i]-'a' ]!=NULL)
now = now->a[ word[i]-'a' ];
else
{
now->a[ word[i]-'a' ] = new node();
now = now->a[ word[i]-'a' ];
}
now->word = true;
}
void dfs(int x,int y, string now, node* tr,vector<vector<char>>& board)
{
if(x<0 || x>=board.size() || y<0 || y>=board[0].size() || board[x][y]==0 || tr->a[ board[x][y]-'a' ]==NULL)
return ;
now = now + board[x][y];
tr = tr->a[ board[x][y]-'a' ];
if(tr->word)
SET.insert(now);
char tmp = board[x][y];
board[x][y] = 0;
dfs(x-1,y,now,tr,board);
dfs(x+1,y,now,tr,board);
dfs(x,y-1,now,tr,board);
dfs(x,y+1,now,tr,board);
board[x][y] = tmp;
}
vector<string> findWords(vector<vector<char>>& board, vector<string>& words)
{
root = new node();
for(int i=0;i<words.size();i++)
insert(words[i]);
for(int i=0;i<board.size();i++)
for(int j=0;j<board[0].size();j++)
dfs(i,j,"",root,board);
vector<string> ans(SET.begin() , SET.end());
return ans;
}
};