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
  | 
struct Trie_Node{
    unordered_map<char, Trie_Node*> children;
    string word;
    Trie_Node(){
        this->word = "";
    }
};
void Insert_Trie(Trie_Node* root, string& s){
    for(auto& c: s){
        if(root->children.count(c) == 0){
            root->children[c] = new Trie_Node();
        }
        root = root->children[c];
    }
    root->word = s;
}
class Solution {
public:
    void dfs(vector<vector<char>>& board, Trie_Node* root, int x, int y, set<string>& ans, int len){
        if(len > 10){
            return;
        }
        char ch = board[x][y];
        if(root->children.count(ch) == 0){
            return;
        }
        
        root = root->children[ch];
        if(root->word != ""){
            ans.insert(root->word);
        }
        // 同一个单词内不允许访问两次,进行标记
        board[x][y] = '#';
        for(int i = 0; i < 4; i++){
            int tx = x + dir[i][0], ty = y + dir[i][1];
            if(tx >= 0 && tx < board.size() && ty >= 0 && ty < board[0].size()){
                if(board[tx][ty] != '#')
                    dfs(board, root, tx, ty, ans, len + 1);
            }
        }
        board[x][y] = ch;
    }
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        Trie_Node* root = new Trie_Node();
        vector<string> res;
        set<string> ans;
        // 把所有需要查询的结点加入到字典树当中
        for(auto& word: words){
            Insert_Trie(root, word);
        }
        // 遍历网格查找是否有合适的单词 
        for(int i = 0; i < board.size(); i++){
            for(int j = 0; j < board[0].size(); j++){
                dfs(board, root, i, j, ans, 0);
            }
        }
        for(auto& word: ans){
            res.push_back(word);        
        }
        
        return res;
    }
};
  |