LeetCode - Word Search II
2015-08-03 14:50
465 查看
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 =
Return
Note:
You may assume that all inputs are consist of lowercase letters
click to show hint.
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.
class TrieNode {
public:
char val;
TrieNode *children[26];
bool tail;
// Initialize your data structure here.
TrieNode() {
val = '\0';
for(int i = 0; i < 26; ++i)
children[i] = nullptr;
tail = false;
}
TrieNode(char c): val(c){
for(int i = 0; i < 26; ++i)
children[i] = nullptr;
tail = false;
}
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
void insert(string word) {
TrieNode *p = root;
int l = word.length();
for(int i = 0; i < l; ++i){
int j = word[i] - 'a';
if(!p->children[j]){
p->children[j] = new TrieNode(word[i]);
}
p = p->children[j];
}
p->tail = true;
}
// Returns if the word is in the trie.
bool search(string word) {
TrieNode *p = root;
int l = word.length();
for(int i = 0; i < l; ++i){
int j = word[i] - 'a';
if(!p->children[j])
return false;
p = p->children[j];
}
return p->tail;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix) {
TrieNode *p = root;
int l = prefix.length();
for(int i = 0; i < l; ++i){
int j = prefix[i] - 'a';
if(!p->children[j])
return false;
p = p->children[j];
}
return true;
}
TrieNode* getRoot(){
return root;
}
private:
TrieNode* root;
};
class Solution {
public:
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
ret.clear();
if(((n = board.size()) == 0) || ((m = board[0].size()) == 0))
return ret;
v = vector<vector<bool>> (n, vector<bool> (m, false));
for(auto &s : words)
trie.insert(s);
TrieNode *root = trie.getRoot();
for(int i = 0; i < n; ++i)
for(int j = 0; j < m; ++j)
if(root->children[board[i][j] - 'a']){
dfs(board, root->children[board[i][j] - 'a'], i, j, string("") + board[i][j]);
}
return ret;
}
private:
Trie trie;
vector<string> ret;
vector<vector<bool>> v;
int n, m;
bool flag = false;
int dx[4] = {0, 0, -1, 1};
int dy[4] = {-1, 1, 0, 0};
void dfs(vector<vector<char> > &board, TrieNode *root, int i, int j, string cur){
if(root->tail){
ret.push_back(cur);
root->tail = false;
}
v[i][j] = true;
for(int d = 0; d < 4; ++ d){
int x = i + dx[d];
int y = j + dy[d];
if(x >= 0 && x < n && y >= 0 && y < m && !v[x][y] && root->children[board[x][y] - 'a']){
dfs(board, root->children[board[x][y] - 'a'], x, y, cur + board[x][y]);
}
}
v[i][j] = false;
}
};
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.
click to show hint.
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.
class TrieNode {
public:
char val;
TrieNode *children[26];
bool tail;
// Initialize your data structure here.
TrieNode() {
val = '\0';
for(int i = 0; i < 26; ++i)
children[i] = nullptr;
tail = false;
}
TrieNode(char c): val(c){
for(int i = 0; i < 26; ++i)
children[i] = nullptr;
tail = false;
}
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
void insert(string word) {
TrieNode *p = root;
int l = word.length();
for(int i = 0; i < l; ++i){
int j = word[i] - 'a';
if(!p->children[j]){
p->children[j] = new TrieNode(word[i]);
}
p = p->children[j];
}
p->tail = true;
}
// Returns if the word is in the trie.
bool search(string word) {
TrieNode *p = root;
int l = word.length();
for(int i = 0; i < l; ++i){
int j = word[i] - 'a';
if(!p->children[j])
return false;
p = p->children[j];
}
return p->tail;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix) {
TrieNode *p = root;
int l = prefix.length();
for(int i = 0; i < l; ++i){
int j = prefix[i] - 'a';
if(!p->children[j])
return false;
p = p->children[j];
}
return true;
}
TrieNode* getRoot(){
return root;
}
private:
TrieNode* root;
};
class Solution {
public:
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
ret.clear();
if(((n = board.size()) == 0) || ((m = board[0].size()) == 0))
return ret;
v = vector<vector<bool>> (n, vector<bool> (m, false));
for(auto &s : words)
trie.insert(s);
TrieNode *root = trie.getRoot();
for(int i = 0; i < n; ++i)
for(int j = 0; j < m; ++j)
if(root->children[board[i][j] - 'a']){
dfs(board, root->children[board[i][j] - 'a'], i, j, string("") + board[i][j]);
}
return ret;
}
private:
Trie trie;
vector<string> ret;
vector<vector<bool>> v;
int n, m;
bool flag = false;
int dx[4] = {0, 0, -1, 1};
int dy[4] = {-1, 1, 0, 0};
void dfs(vector<vector<char> > &board, TrieNode *root, int i, int j, string cur){
if(root->tail){
ret.push_back(cur);
root->tail = false;
}
v[i][j] = true;
for(int d = 0; d < 4; ++ d){
int x = i + dx[d];
int y = j + dy[d];
if(x >= 0 && x < n && y >= 0 && y < m && !v[x][y] && root->children[board[x][y] - 'a']){
dfs(board, root->children[board[x][y] - 'a'], x, y, cur + board[x][y]);
}
}
v[i][j] = false;
}
};
相关文章推荐
- Python Trie树实现字典排序
- Java中实现双数组Trie树实例
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解