LintCode 132. Word Search II -- Trie

Description
Given a matrix of lower alphabets and a dictionary. Find all words in the dictionary that can be found in the matrix. A word can start from any position in the matrix and go left/right/up/down to the adjacent position.

Example
Given matrix:
doaf
agai
dcan
and dictionary:

{“dog”, “dad”, “dgdg”, “can”, “again”}

return {“dog”, “dad”, “can”, “again”}

思路:利用给定的字典构建trie树,减少重复遍历,同时对给定的矩阵进行深度优先搜索,判断给定的字典中的字符串是否存在于矩阵中。
C++ 代码如下:

class TrieNode{
public:
  string str;
  TrieNode* child[26];
  TrieNode(){
      str = "";
      for(int i=0; i<26; ++i) child[i] = NULL;
  }
  void insert(string t, int pos=0)
  {
      if(pos==t.size())
      {
          str = t;
          return;
      }
      int c = t[pos] - 'a';
      if(child[c]==NULL) child[c] = new TrieNode();
      child[c]->insert(t, pos+1);
  }
};

class Solution {
public:
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        TrieNode* node = new TrieNode();
        vector<string> res;
        if(board.size()==0) return res;

        for(int i=0; i<words.size(); ++i)
            node->insert(words[i]);

        for(int i=0; i<board.size(); ++i)
            for(int j=0; j<board[i].size(); ++j)
                search(node, board, i, j, res);
        return res;
    }
     void search(TrieNode* node, vector<vector<char>> &board, int x, int y, vector<string>& res){
        if(x<0 || y<0 || x>=board.size() || y>=board[0].size()) return;
        char c = board[x][y];
         if(c-'a'<0) return;
        TrieNode* cur = node->child[c-'a'];
        if(cur==NULL) return;

        if(cur->str != "")
        {
            res.push_back(cur->str);
            cur->str = "";
        }

        board[x][y] = '#';
        search(cur, board, x+1, y, res);
        search(cur, board, x-1, y, res);
        search(cur, board, x, y+1, res);
        search(cur, board, x, y-1, res);
        board[x][y] = c;

    }
};
阅读更多
想对作者说点什么?
相关热词

博主推荐

换一批

没有更多推荐了,返回首页