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
.
You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier?
If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first.
解题技巧:
前几天刚好学了Trie数据结构,也就是前缀树,这个题可以借助前缀树求解。首先利用已知的单词构建前缀树,然后对board进行DFS,如果当前形成的单词不在Trie里,就不必继续DFS下去,否则,判断当前形成的单词是否为要查找的单词,如果是,将其记录到结果中。
代码:
#include <iostream>
#include <vector>
#include <set>
using namespace std;
class TrieNode {
public:
bool isword;
TrieNode *child[26];
TrieNode(): isword(false)
{
for (int i = 0; i < 26; i ++)
{
child[i] = NULL;
}
}
};
class Trie {
public:
/** Initialize your data structure here. */
Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
void insert(string word) {
TrieNode *p = root;
for(int i = 0; i < word.size(); i++)
{
int t = word[i] - 'a';
if(!p->child[t]) p->child[t] = new TrieNode();
p = p->child[t];
}
p->isword = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
TrieNode *p = root;
for(int i = 0; i < word.size(); i++)
{
int t = word[i] - 'a';
if(!p->child[t]) return false;
p = p->child[t];
}
return p->isword;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
TrieNode *p = root;
for(int i = 0; i < prefix.size(); i++)
{
int t = prefix[i] - 'a';
if(!p->child[t]) return false;
p = p->child[t];
}
return true;
}
private:
TrieNode *root;
};
void dfs(vector< vector<char> >& board, Trie* trie,vector< vector<bool> >& visit, string res0, int x, int y, set<string>& res)
{
int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1},{0, 1}};
int m = board.size(), n = board[0].size();
if(!trie->startsWith(res0))
{
return;
}
if(trie->search(res0))
{
res.insert(res0);
}
if(x >= 0 && x < m && y >= 0 && y < n && visit[x][y] == 0)
{
visit[x][y] = 1;
for(int i = 0; i < 4; i ++)
{
dfs(board, trie, visit, res0+board[x][y], x + dir[i][0], y + dir[i][1], res);
}
visit[x][y] = 0;
}
}
vector<string> findWords(vector< vector<char> >& board, vector<string>& words)
{
int m = board.size(), n = board[0].size();
vector< vector<bool> > visit(m, vector<bool>(n, 0));
set<string> tmp;
vector<string> res;
Trie* trie = new Trie();
for(int i = 0; i < words.size(); i ++)
trie->insert(words[i]);
for(int i = 0; i < m; i ++)
{
for(int j = 0; j < n; j ++)
{
string res0 = "";
dfs(board, trie, visit, res0, i, j, tmp);
}
}
set<string>::iterator it = tmp.begin();
while(it != tmp.end())
{
res.push_back(*it);
it ++;
}
return res;
}
int main()
{
vector< vector<char> > board;
vector<string> words, res;
int m, n;
cin >> m >> n;
for(int i = 0; i < m; i ++)
{
board.push_back(vector<char>(n,' '));
for(int j = 0; j < n; j ++)
{
char c;
cin >> c;
board[i][j] = c;
}
}
string word;
while(cin >> word)
words.push_back(word);
res = findWords(board, words);
for (int i = 0; i < res.size(); i ++)
{
cout<<res[i]<<endl;
}
}
/*
4 4
o a a n
e t a e
i h k r
i f l v
oath
pea
eat
rain
*/