-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWord Search II
87 lines (73 loc) · 2 KB
/
Word Search II
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
class Solution {
struct node
{
char c;
int ends; //can be bool to in this qurstion
string word;
node* child[26];
};
struct node* getNode(char c)
{
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('/');
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=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)
{
int idx = board[i][j]-'a';
if(board[i][j] == '$' || curr->child[idx]==NULL)
return;
curr = curr->child[idx];
if(curr->ends > 0)
{
ans.push_back(curr->word);
curr->ends -= 1;
}
char ch = board[i][j];
board[i][j] = '$';
if(i>0)
solve(board, i-1, j, r,c, ans, curr);
if(i<r-1)
solve(board, i+1, j, r,c, ans, curr);
if(j>0)
solve(board, i, j-1, r,c, ans, curr);
if(j<c-1)
solve(board, i, j+1, r,c, ans, curr);
board[i][j] = ch;
}
public:
vector<string> findWords(vector<vector<char>>& board, vector<string>& words)
{
int r = board.size();
int c = board[0].size();
for(int i=0;i<words.size();i++)
insert(words[i]);
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;
}
};