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;
    }
};
相关推荐
guozhetao31 分钟前
【ST表、倍增】P7167 [eJOI 2020] Fountain (Day1)
java·c++·python·算法·leetcode·深度优先·图论
吃着火锅x唱着歌34 分钟前
LeetCode 611.有效三角形的个数
算法·leetcode·职场和发展
技术卷39 分钟前
详解力扣高频SQL50题之619. 只出现一次的最大数字【简单】
sql·leetcode·oracle
##echo39 分钟前
嵌入式Linux裸机开发笔记9(IMX6ULL)GPIO 中断实验(1)
linux·c语言·笔记·单片机·嵌入式硬件
扶摇直上——————1 小时前
C专题8:文件操作2
c语言·文件操作
我爱学嵌入式3 小时前
C语言第 9 天学习笔记:数组(二维数组与字符数组)
c语言·笔记·学习
qq_513970448 小时前
力扣 hot100 Day56
算法·leetcode
爱装代码的小瓶子10 小时前
数据结构之队列(C语言)
c语言·开发语言·数据结构
爱喝矿泉水的猛男11 小时前
非定长滑动窗口(持续更新)
算法·leetcode·职场和发展
YuTaoShao11 小时前
【LeetCode 热题 100】131. 分割回文串——回溯
java·算法·leetcode·深度优先