Leetcode 212 Word Search II 字典树 + 回溯

来源:互联网 发布:fft算法思想 编辑:程序博客网 时间:2024/05/21 12:13

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.

For example,
Given words = ["oath","pea","eat","rain"] and board =

[  ['o','a','a','n'],  ['e','t','a','e'],  ['i','h','k','r'],  ['i','f','l','v']]
Return ["eat","oath"].

Note:
You may assume that all inputs are consist of lowercase letters a-z.

给一个矩阵,可以从任意一个位置开始,沿水平或垂直方向取连续字符组成字符串,问给定的字符串数组中有多少字符串可以从这个矩阵中生成。

直接套用之前trie的代码。

枚举每一个位置为起点进行dfs,dfs向四个方向搜索,如果当前位置的串不为树中某个词的前缀,则返回,否则看当前串是否为一个存在的单词并继续搜索。

需要注意用一个map维护出现过的单词,避免相同词重复加入结果容器。

同一个位置的字符在一个单词中只能使用一次,因此需要将搜索过的位置置为其他不为字母的字符,并在回溯时调整回来。

class node    {    public:        int flag;        node* next[26];        node(int x = 0)        {            flag = x;            memset(next, 0, sizeof(next));        }    };    class WordDictionary {  public:      node* root;      /** Initialize your data structure here. */      WordDictionary() {          root = new node();      }      /** Adds a word into the data structure. */      void addWord(string word) {          //cout<<word<<endl;        node* p = root;            for(int i = 0; i < word.size(); i++)            {                if(!p->next[word[i] - 'a']) p->next[word[i] - 'a'] = new node();                p = p->next[word[i] - 'a'];            }            p->flag = 1;       }    /** Returns if the word is in the trie. */      bool search(string word)       {          node* p = root;          for(int i = 0; i < word.size(); i++)          {              if(!p->next[word[i] - 'a']) return false;              p = p->next[word[i] - 'a'];          }          return p->flag == 1;      }      /** Returns if there is any word in the trie that starts with the given prefix. */      bool startsWith(string prefix)       {          node* p = root;          for(int i = 0; i < prefix.size(); i++)          {              if(!p->next[prefix[i] - 'a']) return false;              p = p->next[prefix[i] - 'a'];          }          return true;      }  };  class Solution {public:    WordDictionary tree;    unordered_map<string, bool> mp;    void dfs(vector<string> &res, vector<vector<char>>& board, int i,int j, string now)    {        if(board[i][j] == ' ') return ;        now += board[i][j];        if(!tree.startsWith(now)) return ;        if(tree.search(now) && !mp[now])         {            mp[now] = true;            res.push_back(now);        }        char temp = board[i][j];        board[i][j] = ' ';        if(i < board.size() - 1) dfs(res, board, i + 1, j, now);        if(i > 0) dfs(res, board, i - 1, j, now);        if(j < board[0].size() - 1) dfs(res, board, i, j + 1, now);        if(j > 0) dfs(res, board, i, j - 1, now);        board[i][j] = temp;    }    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {        vector<string> res;        int m = board.size();        if(m == 0) return res;        int n = board[0].size();        for(int i = 0; i < words.size(); i++) tree.addWord(words[i]);        for(int i = 0; i < m; i++)        {            for(int j = 0; j < n; j++)            {                string temp;                dfs(res, board, i, j, temp);            }        }        return res;    }};


1 0
原创粉丝点击