|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + vector<string> findWords(vector<vector<char>>& board, vector<string>& words) { |
| 4 | + if (board.empty()) { |
| 5 | + return vector<string>(); |
| 6 | + } |
| 7 | + struct Node { |
| 8 | + Node() { |
| 9 | + id = -1; |
| 10 | + } |
| 11 | + shared_ptr<Node> c[26]; |
| 12 | + int id; |
| 13 | + }; |
| 14 | + using NodePtr = shared_ptr<Node>; |
| 15 | + NodePtr root(new Node()); |
| 16 | + auto insert = [&] (const string &s, int id) { |
| 17 | + NodePtr now = root; |
| 18 | + for (auto c : s) { |
| 19 | + c = c - 'a'; |
| 20 | + if (!now->c[c]) { |
| 21 | + now->c[c] = NodePtr(new Node()); |
| 22 | + } |
| 23 | + now = now->c[c]; |
| 24 | + } |
| 25 | + now->id = id; |
| 26 | + }; |
| 27 | + for (int i = 0; i < words.size(); i++) { |
| 28 | + insert(words[i], i); |
| 29 | + } |
| 30 | + unordered_set<int> res_ids; |
| 31 | + int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0}; |
| 32 | + int n = board.size(), m = board[0].size(); |
| 33 | + vector<vector<bool>> vis(n, vector<bool>(m, false)); |
| 34 | + function<void(int, int, NodePtr)> dfs = [&] (int x, int y, NodePtr now) { |
| 35 | + vis[x][y] = true; |
| 36 | + if (now->id != -1) { |
| 37 | + res_ids.insert(now->id); |
| 38 | + } |
| 39 | + for (int i = 0; i < 4; i++) { |
| 40 | + int xx = x + dx[i]; |
| 41 | + int yy = y + dy[i]; |
| 42 | + if (0 <= xx && xx < n && 0 <= yy && yy < m && !vis[xx][yy]) { |
| 43 | + auto c = board[xx][yy] - 'a'; |
| 44 | + if (now->c[c]) { |
| 45 | + dfs(xx, yy, now->c[c]); |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + vis[x][y] = false; |
| 50 | + }; |
| 51 | + for (int i = 0; i < n; i++) { |
| 52 | + for (int j = 0; j < m; j++) { |
| 53 | + auto c = board[i][j] - 'a'; |
| 54 | + if (root->c[c]) { |
| 55 | + dfs(i, j, root->c[c]); |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + vector<string> ans; |
| 60 | + for (auto id : res_ids) { |
| 61 | + ans.push_back(words[id]); |
| 62 | + } |
| 63 | + return ans; |
| 64 | + } |
| 65 | +}; |
0 commit comments