1
+ class TrieNode {
2
+ public:
3
+ bool isWord;
4
+ TrieNode* child[26 ];
5
+
6
+ TrieNode () {
7
+ isWord = false ;
8
+ for (auto & c : child) {
9
+ c = nullptr ;
10
+ }
11
+ }
12
+ };
13
+
14
+ class Solution {
15
+ int row;
16
+ int col;
17
+ TrieNode* root;
18
+ public:
19
+ void addWord (string word) {
20
+ TrieNode* node = root;
21
+ for (char & c : word) {
22
+ int i = c - ' a' ;
23
+ if (!node->child [i]) {
24
+ node->child [i] = new TrieNode ();
25
+ }
26
+ node = node->child [i];
27
+ }
28
+ node->isWord = true ;
29
+ }
30
+
31
+ void dfs (const vector<vector<char >>& board, int y, int x, TrieNode* node, string word, vector<vector<bool >>& visit, vector<string>& ans) {
32
+ if (x < 0 || y < 0 || x >= col || y >= row || visit[y][x] == true ) {
33
+ return ;
34
+ }
35
+
36
+ char c = board[y][x];
37
+ int token = c - ' a' ;
38
+
39
+ node = node->child [token];
40
+
41
+ if (!node) {
42
+ return ;
43
+ }
44
+
45
+ word += board[y][x];
46
+
47
+ if (node->isWord ) {
48
+ ans.push_back (word);
49
+ node->isWord = false ; // Mark the word as found
50
+ }
51
+
52
+
53
+ visit[y][x] = true ;
54
+ dfs (board, y - 1 , x , node, word, visit, ans);
55
+ dfs (board, y , x + 1 , node, word, visit, ans);
56
+ dfs (board, y + 1 , x , node, word, visit, ans);
57
+ dfs (board, y , x - 1 , node, word, visit, ans);
58
+ visit[y][x] = false ;
59
+ }
60
+
61
+
62
+ vector<string> findWords (vector<vector<char >>& board, vector<string>& words) {
63
+ vector<string> ans;
64
+ row = board.size ();
65
+ col = board[0 ].size ();
66
+
67
+ root = new TrieNode ();
68
+
69
+ for (string& str : words) {
70
+ addWord (str);
71
+ }
72
+
73
+ string key;
74
+ vector<vector<bool >> visit (row, vector<bool >(col, false ));
75
+ for (int i = 0 ; i < row; i++) {
76
+ for (int j = 0 ; j < col; j++) {
77
+ dfs (board, i, j, root, key, visit, ans);
78
+ }
79
+ }
80
+
81
+ return ans;
82
+ }
83
+ };
0 commit comments