博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Word Search II 词语搜索之二
阅读量:6553 次
发布时间:2019-06-24

本文共 2872 字,大约阅读时间需要 9 分钟。

 

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: first.

 

这道题是在之前那道的基础上做了些拓展,之前是给一个单词让判断是否存在,现在是给了一堆单词,让返回所有存在的单词,在这道题最开始更新的几个小时内,用brute force是可以通过OJ的,就是在之前那题的基础上多加一个for循环而已,但是后来出题者其实是想考察字典树的应用,所以加了一个超大的test case,以至于brute force无法通过,强制我们必须要用字典树来求解。LeetCode中有关字典树的题还有和,那么我们在这题中只要实现字典树中的insert功能就行了,查找单词和前缀就没有必要了,然后DFS的思路跟之前那道基本相同,请参见代码如下:

 

class Solution {public:    struct TrieNode {        TrieNode *child[26];        string str;        TrieNode() : str("") {            for (auto &a : child) a = NULL;        }    };    struct Trie {        TrieNode *root;        Trie() : root(new TrieNode()) {}        void insert(string s) {            TrieNode *p = root;            for (auto &a : s) {                int i = a - 'a';                if (!p->child[i]) p->child[i] = new TrieNode();                p = p->child[i];            }            p->str = s;        }    };    vector
findWords(vector
>& board, vector
& words) { vector
res; if (words.empty() || board.empty() || board[0].empty()) return res; vector
> visit(board.size(), vector
(board[0].size(), false)); Trie T; for (auto &a : words) T.insert(a); for (int i = 0; i < board.size(); ++i) { for (int j = 0; j < board[i].size(); ++j) { if (T.root->child[board[i][j] - 'a']) { search(board, T.root->child[board[i][j] - 'a'], i, j, visit, res); } } } return res; } void search(vector
> &board, TrieNode *p, int i, int j, vector
> &visit, vector
&res) { if (!p->str.empty()) { res.push_back(p->str); p->str.clear(); } int d[][2] = { {-1, 0}, { 1, 0}, { 0, -1}, { 0, 1}}; visit[i][j] = true; for (auto &a : d) { int nx = a[0] + i, ny = a[1] + j; if (nx >= 0 && nx < board.size() && ny >= 0 && ny < board[0].size() && !visit[nx][ny] && p->child[board[nx][ny] - 'a']) { search(board, p->child[board[nx][ny] - 'a'], nx, ny, visit, res); } } visit[i][j] = false; }};

 

参考资料:

 

转载地址:http://wvjco.baihongyu.com/

你可能感兴趣的文章
Js模型和封装
查看>>
第二章 Java浮点数精确计算
查看>>
apiCloud实现加载更多效果,基本完美~
查看>>
Redis基准
查看>>
如何使用openssl生成RSA公钥和私钥对
查看>>
当我们安装使用时,会出现eclipse启动不了,出现“Java was started but returned exit code=13......”的问题...
查看>>
2016-2017 ACM-ICPC Southwestern European Regional Programming Contest (SWERC 2016)
查看>>
简明 MongoDB 入门教程
查看>>
.NET Core 3.0中的数据库驱动框架System.Data
查看>>
北大AI公开课2019 | 雷鸣:人工智能革命与机遇
查看>>
英特尔开源计算机视觉数据标签工具CVAT,加速数据注释
查看>>
SQL Server内存泄漏
查看>>
NoSQL生态系统——一致性RWN协议,向量时钟,gossip协议监测故障
查看>>
用Windows Live Writer发布日志到BlogBus
查看>>
解决公司服务器加入域中不能启动应用系统的问题
查看>>
解压缩 操作
查看>>
rsyslog收集nginx日志配置
查看>>
如何判断各种手机浏览器?
查看>>
consule服务注册和发现 安装 部署
查看>>
多个帐户都用root 来登录 怎么看另一个用户使用的那些命令
查看>>