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 分钟前
编辑距离(Edit Distance)——从字符串相似度到动态规划经典模型
算法·leetcode·动态规划
c2385615 分钟前
c/c++中的二叉树进阶
c语言·c++·算法
0x3F(小茶)1 小时前
嵌入式C设计模式完全指南(基于《C嵌入式编程设计模式》)
c语言·开发语言·单片机·嵌入式硬件·设计模式
_日拱一卒1 小时前
LeetCode:46全排列
算法·leetcode·职场和发展
剑挑星河月1 小时前
31.下一个排列
java·算法·leetcode
凌波粒1 小时前
LeetCode--98.验证二叉搜索树(二叉树)
算法·leetcode·职场和发展
Misnearch1 小时前
3635. 最早完成陆地和水上游乐设施的时间II
leetcode·贪心·排序
WWW65262 小时前
代码随想录 打卡第四十七天
数据结构·算法·leetcode
189228048612 小时前
NV022固态MT29F16T08GWLCEM5-QBES:C
c语言·开发语言
cpp_25012 小时前
P10722 [GESP202406 六级] 二叉树
数据结构·c++·算法·题解·洛谷·树形结构·gesp六级