您的位置:首页 > 其它

Leetcode 212. Word Search II

2017-08-10 23:03 435 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Word Search II