Leetcode 212. Word Search II

本文介绍了一种使用回溯和Trie树的方法,在二维字符数组中查找给定单词列表中的所有单词。相邻字母要求同行或同列,并且在匹配过程中每个字母只能使用一次。

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"]

给定多个string组成的数组,要求从一个二维数组里能找到对应的“相邻字母构成这些string”,相邻字母要求:

1 同行或者同列;2 在匹配一个string时同一个字母最多使用一次。

很明显,要得到一个多结果的数组,可以通过回溯实现,由题目提示,用Tris树实现查找。

代码:

class TrieNode {
public:
    vector<TrieNode*> child;
    bool isword;
    // Initialize your data structure here.
    TrieNode() : child(vector<TrieNode*>(26, NULL)), isword(false) {}
};

class Trie {
public:
    Trie() : root(new TrieNode()) {}

    ~Trie() {
        delNode(root);
    }
    
    void delNode(TrieNode* n) {
        for(int i=0; i<26; ++i) {
            if(n->child[i]) delNode(n->child[i]);
        }
        delete n;
    }
    
    TrieNode* getroot() {
        return root;
    }
    
    // Inserts a word into the trie.
    void insert(string word) {
        TrieNode* n = root;
        for(auto ch:word) {
            if(n->child[ch-'a'] == NULL) 
                n->child[ch-'a'] = new TrieNode();
            n = n->child[ch-'a'];
        }
        n->isword = true;
    }

private:
    TrieNode* root;
};

class Solution {
    public:
   void isexist(vector< vector<char> >& board,TrieNode*p,vector<string>&res,string s,int i,int j){
p=p->child[board[i][j]-'a'];
if(p){
    s+=board[i][j];
    if(p->isword){res.push_back(s);p->isword=0;//搜完即失效,以便其它的搜
                  }
    char c=board[i][j];
    board[i][j]=0;//用完一次即可
    if(i>0&&board[i-1][j])isexist(board,p,res,s,i-1,j);
    if(i<board.size()-1&&board[i+1][j])isexist(board,p,res,s,i+1,j);
    if(j>0&&board[i][j-1])isexist(board,p,res,s,i,j-1);
    if(j<board[0].size()-1&&board[i][j+1])isexist(board,p,res,s,i,j+1);
    board[i][j]=c;//还原
      }//存在
}
vector<string> findWords(vector< vector<char> >& board,vector<string>& words){
vector<string>res;
int m=board.size();
if(m<1)return res;
int n=board[0].size();
if(n<1)return res;
Trie t;
for(int i=0;i<words.size();i++)
    t.insert(words[i]);
for(int i=0;i<m;i++)
    for(int j=0;j<n;j++)
	isexist(board,t.getroot(),res,"",i,j);
return res;
}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值