[LeetCode] Word Search II
2015-08-17 22:49
197 查看
A simple combination of Implement Trie (Prefix Tree) and Word Search. If you've solved them, this problem will become easy :-)
The following code is based on DFS and should be self-explanatory enough. Well, just go ahead and read it. It is long but clear :-)
The following code is based on DFS and should be self-explanatory enough. Well, just go ahead and read it. It is long but clear :-)
class TrieNode { public: bool isKey; TrieNode* children[26]; TrieNode() : isKey(false) { memset(children, NULL, sizeof(TrieNode*) * 26); } }; class Trie { public: Trie() { root = new TrieNode(); } void add(string& word) { TrieNode* run = root; for (char c : word) { if (!(run -> children[c - 'a'])) run -> children[c - 'a'] = new TrieNode(); run = run -> children[c - 'a']; } run -> isKey = true; } bool search(string& word) { TrieNode* p = query(word); return p && p -> isKey; } bool startsWith(string& prefix) { return query(prefix) != NULL; } private: TrieNode* root; TrieNode* query(string& s) { TrieNode* run = root; for (char c : s) { if (!(run -> children[c - 'a'])) return NULL; run = run -> children[c - 'a']; } return run; } }; class Solution { public: vector<string> findWords(vector<vector<char>>& board, vector<string>& words) { Trie trie = Trie(); for (string word : words) trie.add(word); int m = board.size(), n = board[0].size(); for (int r = 0; r < m; r++) for (int c = 0; c < n; c++) find(trie, board, "", r, c); return vector<string> (st.begin(), st.end()); } private: unordered_set<string> st; void find(Trie trie, vector<vector<char>>& board, string word, int r, int c) { int m = board.size(), n = board[0].size(); if (board[r][c] == '%') return; word += board[r][c]; if (!trie.startsWith(word)) return; if (trie.search(word)) st.insert(word); board[r][c] = '%'; if (r) find(trie, board, word, r - 1, c); if (r < m - 1) find(trie, board, word, r + 1, c); if (c) find(trie, board, word, r, c - 1); if (c < n - 1) find(trie, board, word, r, c + 1); board[r][c] = word.back(); } };
相关文章推荐
- 【Go语言】【18】GO语言的select
- 【Go语言】【18】GO语言的select
- 做微商还有很长微商卖什么孙佺推广的路要走,还有很多技巧要学习
- 大数据处理初探
- ios学习资料:
- 机器学习实战之KNN算法
- Android SharedPreference配合checkBox完成用户名和密码保存
- DHCP
- Java NIO系列教程(十) Java NIO DatagramChannel
- HDU4497 GCD and LCM
- c++类的初创建(复数类)
- 经典的报数问题
- 使用ApplicationContext作为全局变量引用的缺陷
- Java程序员要求具备的10项技能
- [SQLite]SQL语法
- windows远程桌面域的问题
- 双链表优先队列ADT的实现与测试
- ThreadLocal用法
- 非参数估计-parzen窗估计和k近邻估计
- 【Android源码解析】选择多张图片上传多图预览