C语言 | Leetcode C语言题解之第212题单词搜索II

题目:

题解:

cpp 复制代码
class Solution {
public:
    struct Node{
        int id;
        Node* son[26];
        Node(){
            id = -1;
            for(int i = 0; i < 26; i++) son[i] = NULL;
        }
    }* root;
    vector<vector<char>> g;
    unordered_set<int> ids;
    vector<string> res;
    int dx[4] = {1, -1, 0, 0}, dy[4] = {0, 0, 1, -1};
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        g = board;
        root = new Node();
        for(int i = 0; i < words.size(); i++) {
            string wd = words[i];
            auto p = root;
            for(auto c: wd){
                int i = c - 'a';
                if(!p->son[i]) p->son[i] = new Node();
                p = p->son[i];
            }
            p->id = i;
        }

        for(int i = 0; i < board.size(); i++)
            for(int j = 0; j < board[0].size(); j++){
                int u = g[i][j] - 'a';
                if(root->son[u]) {
                    dfs(i, j, root->son[u]);
                }
            }
        
        for(auto id: ids) res.push_back(words[id]); 
        return res;
    }

    void dfs(int x, int y, Node* root){
        if(root->id != -1) ids.insert(root->id);
        int c = g[x][y];
        g[x][y] = '.';
        for(int i = 0; i < 4; i++){
            int a = x + dx[i], b = y + dy[i];
            if(a < 0 || a >= g.size() || b < 0 || b >= g[0].size() || g[a][b] == '.' ) continue;
            int u = g[a][b] - 'a';
            if(root->son[u]) dfs(a, b, root->son[u]);
        }
        g[x][y] = c;
    }
};
相关推荐
[J] 一坚4 小时前
嵌入式高手C
c语言·开发语言·stm32·单片机·mcu·51单片机·iot
加农炮手Jinx4 小时前
LeetCode 72. Edit Distance 题解
算法·leetcode·力扣
_深海凉_4 小时前
LeetCode热题100-打家劫舍
算法·leetcode·职场和发展
qeen876 小时前
【数据结构】树的基本概念及存储
c语言·数据结构·c++·学习·
pluviophile_s10 小时前
第18讲:⾃定义类型:结构体
c语言·笔记
菜鸟丁小真11 小时前
LeetCode hot100 -73.矩阵置零
数据结构·leetcode·矩阵·知识点总结
We་ct11 小时前
LeetCode 64. 最小路径和:动态规划入门实战
开发语言·前端·算法·leetcode·typescript·动态规划
꧁细听勿语情꧂12 小时前
向下调整算法,top - k 问题,链式结构二叉树,前中后序遍历
c语言·开发语言·数据结构·算法
踩坑记录12 小时前
leetcode hot100 169. 多数元素 easy 技巧 摩尔投票
leetcode
水蓝烟雨13 小时前
3487. 删除后的最大子数组元素和
算法·leetcode·链表