LintCode 132. Word Search II -- Trie

4 篇文章 0 订阅

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;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值