212. Word Search II

来源:互联网 发布:超星视频跳过软件 编辑:程序博客网 时间:2024/05/19 13:55

这道题给了一堆单词,和一个包含很多字母的字典。问这些单词能不能在字典里找到,每次只能从字典的相邻的结点中找。

据说dfs会超时,所以用字典树。

首先把给出的一堆单词建立一个字典树。然后遍历字典的所有字符,如果字典树的这个字符位置不为空,说明有以这个字符开头的单词,调用search函数。从给出字典的当前位置开始,看上下左右哪一个在字典树当前节点中出现,出现的话继续遍历。如果字典树的当前节点已经是字符串而不再是前缀了,就把这个字符串加入结果集。然后把字典树的当前单词删掉。不然的话,字典{‘a’}单词{"a", "a"}的结果是{"a", "a"},但是正确的结果是{"a"}。

class Solution {public:    struct TrieNode{        TrieNode *child[26];        string str;        TrieNode():str(""){            for(auto &a : child)                a = NULL;        }    };    struct Trie{        TrieNode *root;        Trie() : root(new TrieNode()){}        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->str = s;        }    };    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {        vector<string> res;        if(words.empty() || board.empty() || board[0].empty())  return {};        vector<vector<bool>> visit(board.size(), vector<bool>(board[0].size(), false));        Trie T;        for(auto &a : words)    T.insert(a);        for(int i = 0; i < board.size(); ++i){            for(int j = 0; j < board[i].size(); ++j){                if(T.root->child[board[i][j] - 'a']){                    search(board, T.root->child[board[i][j] - 'a'], i, j, visit, res);                }            }        }        return res;    }    void search(vector<vector<char>> &board, TrieNode *p, int i, int j, vector<vector<bool>> &visit, vector<string> &res){        if(!p->str.empty()){            res.push_back(p->str);            p->str.clear();        }        int d[][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};        visit[i][j] = true;        for(auto &a : d){            int nx = a[0] + i, ny = a[1] + j;            if(nx >= 0 && nx < board.size() && ny >= 0 && ny < board[0].size() && !visit[nx][ny] && p->child[board[nx][ny] - 'a']){                search(board, p->child[board[nx][ny] - 'a'], nx, ny, visit, res);            }        }        visit[i][j] = false;    }};