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;
    }
};
相关推荐
Word码1 小时前
[排序算法]希尔排序
c语言·数据结构·算法·排序算法
来生硬件工程师2 小时前
【STM32笔记】:P03 ISP 一键下载电路详解
c语言·笔记·stm32·嵌入式硬件·硬件工程·接口隔离原则·硬件设计
biter down3 小时前
c语言14:字符指针
c语言·开发语言
一念&5 小时前
每日一个C语言知识:C 字符串
c语言·开发语言
DuHz6 小时前
C程序中的数组与指针共生关系
linux·c语言·开发语言·嵌入式硬件·算法
而后笑面对6 小时前
力扣2025.10.19每日一题
算法·leetcode·职场和发展
来生硬件工程师6 小时前
【STM32笔记】:P04 断言的使用
c语言·笔记·stm32·单片机·嵌入式硬件·硬件架构·硬件设计
·白小白6 小时前
力扣(LeetCode) ——11.盛水最多的容器(C++)
c++·算法·leetcode
yuuki2332337 小时前
【C语言】文件操作(附源码与图片)
c语言·后端
秦.赢渠梁8 小时前
各种通信(三):GPS模块数据解析
c语言