LeetCode 212. 单词搜索 II

LeetCode 212. 单词搜索 II
LeetCode 212. 单词搜索 II_第1张图片
字典树 + dfs

const int N = 3e4 + 10, M = 15;
class Solution {
public:
    int son[N][26], cnt[N], idx = 0;
    bool st[M][M] = {0};
    int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
    vector<string> res;
    int n, m;
    void insert(string str)
    {
        int p = 0;
        for(int i = 0; str[i]; i ++)
        {
            int u = str[i] - 'a';
            if(!son[p][u]) son[p][u] = ++ idx;
            p = son[p][u];
        }
        // cout <<"p"<< p << endl;
        cnt[p] ++;
        // cout <<"cnt"<< p[cnt] << endl;
    }
    void dfs(vector<vector<char>>& board, int i, int j, int p,string word)
    {
        if(st[i][j]) return;
        char c = board[i][j];
        int u = c - 'a';
        if(son[p][u] == 0) return;

        p = son[p][u];
        // cout << p << endl;
        if(cnt[p])
        {
            res.push_back(word + c);
            cnt[p] = 0;
        }
        st[i][j] = true;
        for(int k = 0; k < 4; k ++)
        {
            int a = i + dx[k], b = j + dy[k];
            if(a < 0 || a >= n || b < 0 || b >= m) continue;

            dfs(board, a, b, p, word + c);
        }
        st[i][j] = false;
    }
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        
        for(auto w : words)
            insert(w);

        n = board.size(), m = board[0].size();

        for(int i = 0; i < n; i ++)
            for(int j = 0; j < m; j ++)
                dfs(board, i, j, 0, "");

        return res;
    }
};

你可能感兴趣的:(算法,leetcode,深度优先,算法,字典树)