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;
    }
};
相关推荐
HABuo3 小时前
【linux文件系统】磁盘结构&文件系统详谈
linux·运维·服务器·c语言·c++·ubuntu·centos
alphaTao8 小时前
LeetCode 每日一题 2026/2/2-2026/2/8
算法·leetcode
甄心爱学习8 小时前
【leetcode】判断平衡二叉树
python·算法·leetcode
不知名XL8 小时前
day50 单调栈
数据结构·算法·leetcode
2401_858936889 小时前
【Linux C 编程】标准 IO 详解与实战:从基础接口到文件操作实战
linux·c语言
@––––––9 小时前
力扣hot100—系列2-多维动态规划
算法·leetcode·动态规划
YuTaoShao10 小时前
【LeetCode 每日一题】1653. 使字符串平衡的最少删除次数——(解法三)DP 空间优化
算法·leetcode·职场和发展
cpp_250110 小时前
P10570 [JRKSJ R8] 网球
数据结构·c++·算法·题解
cpp_250110 小时前
P8377 [PFOI Round1] 暴龙的火锅
数据结构·c++·算法·题解·洛谷
TracyCoder12311 小时前
LeetCode Hot100(26/100)——24. 两两交换链表中的节点
leetcode·链表