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;
    }
};
相关推荐
少司府2 分钟前
C++基础入门:类和对象(上)
c语言·开发语言·c++·类和对象·访问限定符
.柒宇.25 分钟前
力扣hot 100之和为 K 的子数组(Java版)
java·算法·leetcode
Byte不洛27 分钟前
LeetCode中经典双指针题(环形链表 + 快乐数 + 移动零)
算法·leetcode·链表·数组·双指针
老师用之于民32 分钟前
【DAY35】ARM开发:UART 异步串行通信原理、通信标准及模块配置详解
c语言·汇编·arm开发·vscode
阿豪学编程10 小时前
LeetCode724.:寻找数组的中心下标
算法·leetcode
禹中一只鱼11 小时前
【力扣热题100学习笔记】 - 哈希
java·学习·leetcode·哈希算法
凌波粒11 小时前
LeetCode--349.两个数组的交集(哈希表)
java·算法·leetcode·散列表
我叫洋洋12 小时前
[Proteus 和 stm32f103c8t6]的使用控制OLED篇]
c语言·stm32·单片机·嵌入式硬件·蓝桥杯·proteus
Book思议-13 小时前
【数据结构】栈与队列全方位对比 + C 语言完整实现
c语言·数据结构·算法··队列
IT方大同16 小时前
(实时操作系统)线程管理
c语言·开发语言·嵌入式硬件