1. 程式人生 > >【LeetCode】212. Word Search II

【LeetCode】212. Word Search II

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();
    }
};