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;
    }
};
相关推荐
望酹江月1 小时前
HNU-RFID与传感器原理实验
c语言·单片机
阿里嘎多哈基米1 小时前
速通Hot100-Day09——二叉树
算法·leetcode·二叉树·hot100
Frostnova丶1 小时前
LeetCode 48 & 1886.矩阵旋转与判断
算法·leetcode·矩阵
多打代码1 小时前
2026.3.22 回文子串
算法·leetcode·职场和发展
im_AMBER1 小时前
Leetcode 144 位1的个数 | 只出现一次的数字
学习·算法·leetcode
小刘不想改BUG2 小时前
LeetCode 138.随机链表的复制 Java
java·leetcode·链表·hash table
计算机安禾2 小时前
【C语言程序设计】第39篇:预处理器与宏定义
c语言·开发语言·c++·vscode·算法·visual studio code·visual studio
参.商.2 小时前
【Day43】49. 字母异位词分组
leetcode·golang
参.商.3 小时前
【Day45】647. 回文子串 5. 最长回文子串
leetcode·golang
本喵是FW3 小时前
C语言手记3
c语言·开发语言