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
| class Solution { public: vector<string> findWords(vector<vector<char>>& board, vector<string>& words) { if (board.empty() || board[0].empty()) return {}; TrieNode *root = new TrieNode; for (const auto &w : words) { insert(root, w); } vector<string> res; int dx[] = {0, 0, -1, 1}, dy[] = {-1, 1, 0, 0}; for (int i = 0; i < board.size(); ++i) { for (int j = 0; j < board[i].size(); ++j) { dfs(root, board, i, j, dy, dx, res); } } return res; }
struct TrieNode { TrieNode *children[26] = {nullptr}; string w; };
void insert(TrieNode *p, const string &word) { for (char c : word) { if (!p->children[c - 'a']) { p->children[c - 'a'] = new TrieNode; } p = p->children[c - 'a']; } p->w = word; }
void dfs(TrieNode *p, vector<vector<char>> &board, int i, int j, int dy[], int dx[], vector<string> &res) { if (i < 0 || j < 0 || i == board.size() || j == board[0].size() || board[i][j] == '#' || !p->children[board[i][j] - 'a']) return; char c = board[i][j]; p = p->children[c - 'a']; if (!p->w.empty()) { res.push_back(p->w); p->w.clear(); } board[i][j] = '#'; for (int k = 0; k < 4; ++k) { dfs(p, board, i + dy[k], j + dx[k], dy, dx, res); } board[i][j] = c; } };
|