【LeetCode】212. Word Search II

35 篇文章 2 订阅
4 篇文章 0 订阅

Given a 2D board and a list of words from the dictionary, find all words in the board.

Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.

Example:

Input: 
words = ["oath","pea","eat","rain"] and board =
[
  ['o','a','a','n'],
  ['e','t','a','e'],
  ['i','h','k','r'],
  ['i','f','l','v']
]

Output: ["eat","oath"]

题解:主框架同之前的word search直接回溯,但是如果对每一个字符串都进行回溯会超时,此时需要只遍历一次图然后每个点回溯过程中便把words里的字符串全部搜索,这里需要用tire的数据结构,利用字典树,相当于之前只是遍历一个word现在遍历一棵树,遍历树的过程遇到单词则加入ans,这里遇到了很难发现的bug主要对回溯法没理解清楚,首先我传入一个string tmp,如果用引用类型在回溯返回的过程中如果没有pop会一直加下去

代码:

class TrieNode {
public:
    // Initialize your data structure here.
    TrieNode *child[26];
    bool isWord;
    TrieNode() : isWord(false){
        for (auto &a : child) a = NULL;
    }
};

class Trie {
public:
    TrieNode* root;
    Trie() {
        root = new TrieNode();
    }

    // Inserts a word into the trie.
    void insert(string s) {
        TrieNode *p = root;
        for (auto &a : s) {
            int i = a - 'a';
            if (!p->child[i]) p->child[i] = new TrieNode();
            p = p->child[i];
        }
        p->isWord = true;
    }


    
};
class Solution {
    
public:
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        Trie* trie=new Trie();
        for(auto& w:words){
            trie->insert(w);
        }
        TrieNode* root=trie->root;
        vector<string> ans;
        for(int i=0;i<board.size();i++){
            for(int j=0;j<board[0].size();j++){
                string tmp;
                dfs(root,board,ans,tmp,i,j);
            }
        }
        return ans;
    }
    void dfs(TrieNode* root,vector<vector<char>>& G,vector<string>& ans,string& tmp,int i,int j){
        
        
        if(i<0||j<0||i>=G.size()||j>=G[0].size()||G[i][j]=='*') return;        
        char c=G[i][j];
        if(root->child[c-'a']){
            root=root->child[c-'a'];
        }else return;
        tmp+=G[i][j];

        if(root->isWord) {
            ans.push_back(tmp);root->isWord=false;
        }
         
        G[i][j]='*';
        dfs(root,G,ans,tmp,i+1,j);
        dfs(root,G,ans,tmp,i-1,j);
        dfs(root,G,ans,tmp,i,j+1);
        dfs(root,G,ans,tmp,i,j-1);
        G[i][j]=c;
        tmp.pop_back();
    }
};




 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值