212. 单词搜索 II

89 阅读1分钟

212. 单词搜索 II

知识点:Trie字典树

struct TrieNode {
    string word;
    unordered_map<char, TrieNode *> children;
    TrieNode() {
        this->word = "";
    }
};

void insertTrie(TrieNode *root, const string & word) {
    TrieNode *node = root;
    for (auto c : word) {
        if (!node->children.count(c)) node->children[c] = new TrieNode();
        node = node->children[c];
    }
    node->word = word;
}

class Solution {
private:
    int n, m;

public:
    const int dx[4] = {0, 1, 0, -1};
    const int dy[4] = {-1, 0, 1, 0};

    bool check(int x, int y) {
        return x >= 0 && x < n && y >= 0 && y < m;
    }

    bool dfs(vector<vector<char>>& board, int x, int y, TrieNode *root, set<string> &res) {
        char c = board[x][y];
        if (root == nullptr || !root->children.count(c)) return false;
        TrieNode *nxt = root->children[c];
        if (nxt->word.size() > 0) res.insert(nxt->word), nxt->word = "";
        board[x][y] = '#';
        for (int i = 0; i < 4; ++i) {
            int xx = x + dx[i], yy = y + dy[i];
            if (check(xx, yy) && board[xx][yy] != '#') dfs(board, xx, yy, nxt, res);
        } 
        board[x][y] = c;
        if (nxt->children.empty()) root->children.erase(c);
        return true;
    }

    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        this->n = board.size(); this->m = board[0].size();
        TrieNode *root = new TrieNode();
        set<string> res;
        vector<string> ans;
        for (auto &s : words) insertTrie(root, s);
        for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) dfs(board, i, j, root, res);
        for (auto &s : res) ans.push_back(s);
        return ans;
    }
};