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;
    }
};
相关推荐
HZ·湘怡19 小时前
数据结构之排序算法 (1)--插入排序
c语言·数据结构·算法·排序算法
开源Z19 小时前
LeetCode 238 · 除自身以外数组的乘积:左右两遍扫描,不用除法
算法·leetcode
BAGAE20 小时前
FEC-RS前向纠错编码理论及工程实施研究
c语言·c++·qt·算法·决策树·链表
8Qi820 小时前
LeetCode 5:最长回文子串(Longest Palindromic Substring)—— 题解
算法·leetcode·职场和发展·动态规划
wuminyu21 小时前
Java锁机制之park与futex系统级协同机制解析
java·linux·c语言·jvm·c++
caimouse1 天前
reactos编码规范
c语言·开发语言
AI thought1 天前
【转】C语言中 -> 是什么意思?
c语言·位移运算符·右移赋值·无符号整数·算术右移
如竟没有火炬1 天前
最大矩阵——单调栈
数据结构·python·线性代数·算法·leetcode·矩阵
8Qi81 天前
LeetCode 1143 & 718:最长公共子序列 / 最长重复子数组
算法·leetcode·职场和发展·动态规划
想吃火锅10051 天前
【leetcode】1.两数之和js版
javascript·算法·leetcode