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;
    }
};
相关推荐
mask哥3 小时前
力扣算法java实现汇总整理(上)
java·算法·leetcode
袁雅倩19974 小时前
当吸尘器、筋膜枪都用上Type-C,供电方案该怎么选?浅谈PD取电芯片ECP5702的应用
c语言·开发语言·支持向量机·动态规划·推荐算法·最小二乘法·图搜索算法
流年如夢7 小时前
栈和列队(LeetCode)
数据结构·算法·leetcode·链表·职场和发展
CHANG_THE_WORLD9 小时前
C语言中的 %*s 和 %.*s 和C++的字符串格式化输出
c语言·c++·c#
消失的旧时光-19439 小时前
C语言对象模型系列(四)《Linux 内核里的 container_of 到底是什么黑魔法?》—— 一篇讲透 Linux 内核的“对象模型”核心技巧
linux·c语言·算法
2501_9318037510 小时前
Go:一门为解决C语言痛点而生的现代语言
c语言·开发语言·golang
qeen8710 小时前
【数据结构】二叉树相关经典函数C语言实现
c语言·数据结构·c++·笔记·学习·算法·二叉树
星星码️12 小时前
LeetCode刷题简单篇之反转字母
c++·算法·leetcode
Hello.Reader12 小时前
ds4.c 深度解析为 DeepSeek V4 Flash 打造的本地推理引擎
c语言·开发语言
谙弆悕博士14 小时前
快速学C语言—— 第0章:C语言简介
c语言·开发语言·经验分享·笔记·程序人生·课程设计·学习方法