Skip to content

Commit

Permalink
Update and rename 212.Word-Search-II.cpp to 212.Word-Search-II_v1.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
wisdompeak authored Apr 24, 2021
1 parent 17c9817 commit 33e5074
Showing 1 changed file with 28 additions and 33 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,53 +12,46 @@ class Solution {
}
};
TrieNode* root;
set<string>Set;
int M;
int N;
unordered_set<string>Set;
int M, N;
bool visited[12][12];
public:
vector<string> findWords(vector<vector<char>>& board, vector<string>& words)
{
root=new TrieNode();

for (int i=0; i<words.size(); i++)
build(words[i]);

M=board.size();
N=board[0].size();
auto visited=vector<vector<int>>(M,vector<int>(N,0));
N=board[0].size();
root=new TrieNode();
for (int i=0; i<words.size(); i++)
{
TrieNode* node=root;
for (auto ch: words[i])
{
if (node->next[ch-'a']==NULL)
node->next[ch-'a']=new TrieNode();
node=node->next[ch-'a'];
}
node->isEnd=true;
}

string word;
for (int i=0; i<M; i++)
for (int j=0; j<N; j++)
{
{
TrieNode* node = root;
string word;
visited[i][j]=1;
DFS(i,j,root,word,visited,board);
DFS(i,j,node,word,board);
visited[i][j]=0;
}

vector<string>results(Set.begin(),Set.end());
return results;
}

void build(string word)
{
TrieNode* node=root;
for (int i=0; i<word.size(); i++)
{
char ch=word[i];
if (node->next[ch-'a']==NULL)
node->next[ch-'a']=new TrieNode();
node=node->next[ch-'a'];
}
node->isEnd=true;
}

void DFS(int i, int j, TrieNode* node, string word, vector<vector<int>>&visited, vector<vector<char>>& board)
void DFS(int i, int j, TrieNode* node, string& word, vector<vector<char>>& board)
{
if (node->next[board[i][j]-'a']==NULL) return;

if (node->next[board[i][j]-'a']==NULL) return;
node = node->next[board[i][j]-'a'];
word += board[i][j];
word.push_back(board[i][j]);

if (node->isEnd==true) Set.insert(word);

Expand All @@ -71,9 +64,11 @@ class Solution {
if (x<0||x>=M||y<0||y>=N) continue;
if (visited[x][y]==1) continue;

visited[x][y]=1;
DFS(x,y,node,word,visited,board);
visited[x][y]=0;
visited[x][y]=1;
DFS(x,y,node,word,board);
visited[x][y]=0;
}

word.pop_back();
}
};

0 comments on commit 33e5074

Please sign in to comment.