【DFS+Trie】力扣热题100-单词搜索

一、题目

. - 力扣(LeetCode). - 备战技术面试?力扣提供海量技术面试资源,帮助你高效提升编程技能,轻松拿下世界 IT 名企 Dream Offer。icon-default.png?t=N7T8https://leetcode.cn/problems/word-search/description/?envType=study-plan-v2&envId=top-100-liked

二、题解

本题是单词搜索II的特殊情况,单词搜索II需要用到Trie树本题可以不使用Trie树但思想总体上相同,都是枚举所有可能的单词序列,看该序列是否是目标单词或者目标单词的前缀,如果是目标单词则之间返回,如果是前缀则继续dfs

const int N = 1e4 + 10;
class Solution {
public:

    int son[N][128], cnt[N], idx, n, m; // son存储Trie树,cnt存储该位置结尾是否有单词,idx用于申请空间
    vector<vector<char>> words;  // 将字符矩阵参数全局
    string path;                 // 记录dfs过程中的单词序列
    bool check[10][10];          // dfs过程中用于标记已经选择的字符
    bool dfs(int i, int j) {
        path.push_back(words[i][j]);
        check[i][j] = true;
        if (search(path)) return true;
        if (!prefix(path)) {     // 剪枝
            check[i][j] = false;
            path.pop_back();
            return false;
        };
        bool ans = false;
        if (i - 1 >= 0 && !check[i - 1][j]) {
            ans |= dfs(i - 1, j);
        }

        if (i + 1 < n && !check[i + 1][j]){
            ans |= dfs(i + 1, j);
        }

        if (j - 1 >= 0 && !check[i][j - 1]) {
            ans |= dfs(i, j - 1);
        }

        if (j + 1 < m && !check[i][j + 1]) {
            ans |= dfs(i, j + 1);
        }

        check[i][j] = false;
        path.pop_back();
        return ans;
    }


    void insert(string path) {
        int p = 0;
        for (auto x : path) {
            int childIndex = x - 'A';
            if (!son[p][childIndex]) son[p][childIndex] = ++idx;
            p = son[p][childIndex];
        }
        cnt[p]++;
    }

    bool search(string path) {
        int p = 0;
        for (auto x : path) {
            int childIndex = x - 'A';
            if (!son[p][childIndex]) return 0;
            p = son[p][childIndex];
        }
        return cnt[p];
    }

    bool prefix(string path) {
        int p = 0;
        for (auto x : path) {
            int childIndex = x - 'A';
            if (!son[p][childIndex]) return 0;
            p = son[p][childIndex];
        }
        return 1;
    }

    bool exist(vector<vector<char>>& board, string word) {
        idx = 0;
        memset(son, 0, sizeof(son));
        memset(cnt, 0, sizeof(cnt));
        insert(word);
        
        words = board;
        n = board.size(), m = board[0].size();
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                if (dfs(i, j)) 
                    return true;
        return false;
    }
};
  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值