-
Notifications
You must be signed in to change notification settings - Fork 0
/
212 Word Search II.cpp
98 lines (89 loc) · 2.44 KB
/
212 Word Search II.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
static int fastio=[](){
#define endl '\n'
std::ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}();
/*
Source:
https://youtu.be/EmvsBM7o-5k
*/
class Solution {
private:
struct node{ //TrieNode
char c;
int ends;
string word;
node *child[26];
};
struct node *getNode(char c) //get newnode
{
node *newnode = new node;
newnode->c = c;
newnode->ends = 0;
newnode->word = "";
for(int i=0;i<26;++i)
newnode->child[i] = NULL;
return newnode;
}
node *root = getNode('/'); //root
//Trie INSERT
void insert(string s)
{
node *curr=root;
int index,i=0;
while(s[i])
{
index = s[i]-'a';
if(curr->child[index]==NULL)
curr->child[index] = getNode(s[i]);
curr=curr->child[index];
i+=1;
}
curr->ends += 1;
curr->word = s;
}
void solve(vector<vector<char>>& board,int i,int j,int r,int c,vector<string>& ans,node *curr)
{
//Base case
//If the trie doesn't have the current char OR cell is Visited
int index = board[i][j]-'a';
if(board[i][j]=='$' || curr->child[index]==NULL)
return;
curr = curr->child[index];
if(curr->ends > 0)
{
ans.push_back(curr->word);
curr->ends -=1;
}
//Body
char ch = board[i][j]; //Store current char
board[i][j] = '$'; //Mark current node visited
if(i>0) //TOP
solve(board,i-1,j,r,c,ans,curr);
if(i<r-1) //DOWN
solve(board,i+1,j,r,c,ans,curr);
if(j>0) //LEFT
solve(board,i,j-1,r,c,ans,curr);
if(j<c-1) //RIGHT
solve(board,i,j+1,r,c,ans,curr);
board[i][j] = ch; //Mark current node as Unvisited by restoring the value
}
public:
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
int r=board.size();
int c=board[0].size();
//Insert all words in TRIE
for(int i=0;i<words.size();++i)
insert(words[i]);
//Now search words
vector<string> ans;
for(int i=0;i<r;++i)
{
for(int j=0;j<c;++j)
solve(board,i,j,r,c,ans,root);
}
return ans;
}
};