forked from Mohammed-Shoaib/Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC0212.cpp
More file actions
executable file
·83 lines (68 loc) · 1.6 KB
/
LC0212.cpp
File metadata and controls
executable file
·83 lines (68 loc) · 1.6 KB
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
/*
Problem Statement: https://leetcode.com/problems/word-search-ii/
Time: O(n • m • 3ˡᵉⁿ)
Space: O(words • len)
*/
class TrieNode {
public:
bool end;
unordered_map<char, TrieNode*> children;
TrieNode() : end(false) {}
TrieNode* get_next(char& c) {
if (children.count(c))
return children[c];
else
return nullptr;
}
};
class Trie {
public:
TrieNode* root;
Trie() : root(new TrieNode()) {}
void add(string& word) {
TrieNode* node = root;
for (char& c: word) {
if (!node->children.count(c))
node->children[c] = new TrieNode();
node = node->children[c];
}
node->end = true;
}
void build(vector<string>& words) {
for (string& word: words)
add(word);
}
};
class Solution {
public:
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
int m, n;
m = board.size();
n = board[0].size();
Trie trie;
string word;
vector<string> res;
vector<int> xdir = {-1, 0, 1, 0}, ydir = {0, -1, 0, 1};
// helper function
function<void(int, int, TrieNode*)> search = [&](int i, int j, TrieNode* node) {
// base cases
if (i < 0 || i == m || j < 0 || j == n || !node->get_next(board[i][j]))
return;
node = node->get_next(board[i][j]);
word += exchange(board[i][j], '*');
for (int k = 0; k < xdir.size(); k++)
search(i + xdir[k], j + ydir[k], node);
if (node->end) {
node->end = false;
res.push_back(word);
}
board[i][j] = word.back();
word.pop_back();
};
trie.build(words);
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
search(i, j, trie.root);
return res;
}
};