LeetCode 212. 单词搜索 II

LeetCode 212. 单词搜索 II
在这里插入图片描述
字典树 + 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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值