from : https://leetcode.com/problems/word-search-ii/
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"].class Solution {
public:
struct TrieNode {
bool isWord;
TrieNode *nextNodes[26];
TrieNode(): isWord(false){
for(TrieNode*& c : nextNodes) {
c = NULL;
}
}
void becomeWord() {
isWord = true;
}
void setNext(char next) {
nextNodes[next-'a'] = new TrieNode();
}
TrieNode* next(char next) {
return nextNodes[next-'a'];
}
};
struct Trie {
Trie() {
root = new TrieNode();
}
void insert(string& word) {
TrieNode *p = root;
for(char c : word) {
if(NULL == p->next(c)) {
p->setNext(c);
}
p = p->next(c);
}
p->becomeWord();
}
bool containWordStartWith(char character) {
return NULL != root->nextNodes[character-'a'];
}
TrieNode* begin() {
return root;
}
private :
TrieNode *root;
};
bool isWithinBoundry(int i, int j) {
if(i<0 || i>=m || j<0 || j>=n) {
return false;
}
return true;
}
void find(vector<vector<char>>& board, int i, int j, set<string>& st, vector<vector<bool>>& visit, string& str, TrieNode* trienode) {
trienode = trienode->next(board[i][j]);
if(!trienode) return;
visit[i][j] = true;
str.push_back(board[i][j]);
if(trienode->isWord) {
st.insert(str);
}
int dx[] = {1,0,-1,0};
int dy[] = {0,1,0,-1};
int x, y;
for(int k=0; k<4; ++k) {
x = i + dx[k];
y = j + dy[k];
if(isWithinBoundry(x, y) && !visit[x][y]) {
if(trienode->next(board[x][y])) {
find(board, x, y, st, visit, str, trienode);
}
}
}
str.pop_back();
visit[i][j] = false;
}
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
vector<string> res;
if(words.empty() || board.empty() || board[0].empty()) {
return res;
}
Trie trie;
for(string& s : words) {
trie.insert(s);
}
m = board.size(), n = board[0].size();
vector<vector<bool>> visit(m, vector<bool>(n, false));
set<string> st;
string str;
for(int i=0; i<m; ++i) {
for(int j=0; j<n; ++j) {
if(trie.containWordStartWith(board[i][j])) {
find(board, i, j, st, visit, str, trie.begin());
}
}
}
for(string s : st) {
res.push_back(s);
}
return res;
}
private:
int m;
int n;
};
LeetCode单词搜索II题解
本文介绍了一种使用字典树(Trie)结构解决LeetCode上的单词搜索II问题的方法。通过构建字典树来高效查找给定二维字母板上出现的所有字典中的单词。该算法采用深度优先搜索策略,结合回溯思想,确保每个字母只被使用一次构建单词。

被折叠的 条评论
为什么被折叠?



