LC-212. 单词搜索 II
作者:互联网
- 单词搜索 II
给定一个 m x n 二维字符网格 board 和一个单词(字符串)列表 words,找出所有同时在二维网格和字典中出现的单词。
单词必须按照字母顺序,通过 相邻的单元格 内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。
示例 1:
输入:board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
输出:["eat","oath"]
类似于前缀树,在建树的时候只在叶子结点存储string,每个节点都是map存储26个字符所对应的指针
class Solution {
private:
set<string> res;
int m, n;
struct TreeNode {
map<char, TreeNode*> child;
string word;
TreeNode () {
word = "";
}
};
public:
void insertTree (TreeNode* root, string word) {
TreeNode *node = root;
for (char &k : word) {
//这里表示新建节点
if (!node -> child.count(k)) {
node -> child[k] = new TreeNode();
}
node = node ->child[k];
}
//在叶子节点出存储string
node -> word = word;
}
int dir[4][2] = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}};
void dfs (vector<vector<char>>& board, int i, int j, TreeNode* root) {
char ch = board[i][j];
if (!root -> child.count(ch)) {
return;
}
//到达这里就表明存在这个单词的这个字符,而且存储的字符串长度大于0,表示可以生成这个单词
root = root -> child[ch];
if (root -> word.size() > 0) {
res.insert(root -> word);
}
board[i][j] = '#';
for (int k = 0; k < 4; k++) {
int xx = i + dir[k][0], yy = j + dir[k][1];
if (xx < 0 || xx >= m || yy < 0 || yy >= n || board[xx][yy] == '#') {
}else {
dfs (board, xx, yy, root);
}
}
board[i][j] = ch;
}
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
TreeNode *root = new TreeNode();
for (string &k : words) {
insertTree(root, k);
}
m = board.size(), n = board[0].size();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
dfs(board, i, j, root);
}
}
vector<string> ans(res.begin(), res.end());
return ans;
}
};
标签:单词,TreeNode,LC,int,word,II,board,212,root 来源: https://www.cnblogs.com/smilerain/p/15307446.html