leetcode 212. Word Search II
来源:互联网 发布:java b2b2c 开源 编辑:程序博客网 时间:2024/03/29 22:48
trie + backtracking
class Solution {public:vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {TrieNode* root = new TrieNode();for (auto str : words)insert(root, str);visited.resize(board.size(), vector<bool>(board[0].size(), false));for (int row = 0; row < board.size(); ++row)for (int col = 0; col < board[row].size(); ++col)backTrack(root, board, row, col, "");vector<string> ret;for (auto elem : set_ret)ret.push_back(elem);return ret;}private:vector<vector<bool>> visited;set<string> set_ret;struct TrieNode {const static unsigned LETTERS_NUM = 26;bool hasString;struct TrieNode* next[LETTERS_NUM];TrieNode() : hasString(false) {for (int i = 0; i < LETTERS_NUM; ++i)next[i] = NULL;}};void insert(TrieNode* root, string str) {string::size_type i = 0;TrieNode* ptr = root;while (i < str.size()) {if (!ptr->next[str[i] - 'a'])ptr->next[str[i] - 'a'] = new TrieNode();ptr = ptr->next[str[i] - 'a'];i++;}ptr->hasString = true; // 允许空字符串}void backTrack(TrieNode* root, vector<vector<char>>& board, int row, int col, string str) {auto child = root->next[board[row][col] - 'a']; /*尽量避免这样写, 之前visited[row][col]=true写在第一行, 导致 visited[row][col] = false无法执行 */if (!child) return;visited[row][col] = true;str += board[row][col];if (child->hasString)set_ret.insert(str);int dir[4][2] = { { 1, 0 },{ 0, 1 },{ -1, 0 },{ 0, -1 } };for (int i = 0; i < 4; ++i) {int r = dir[i][0] + row,c = dir[i][1] + col;/* 屡次犯的低级错误 * if ( !visited[r][c] &&r >= 0 && r < board.size() && c >= 0 && c < board[r].size()) */if (r >= 0 && r < board.size() && c >= 0 && c < board[r].size() && !visited[r][c])backTrack(child, board, r, c, str);}visited[row][col] = false;}};
0 0
- [leetcode] 212.Word Search II
- LeetCode 212. Word Search II
- leetcode.212. Word Search II
- [leetcode] 212. Word Search II
- Leetcode 212. Word Search II
- leetcode 212. Word Search II
- Leetcode 212. Word Search II
- Leetcode 212. Word Search II
- Leetcode 212. Word Search II
- LeetCode 212. Word Search II
- Leetcode 212. Word Search II
- LeetCode Word Search II
- [leetcode] Word Search II
- LeetCode Word Search II
- leetcode Word Search II
- LeetCode - Word Search II
- [leetcode]Word Search II
- leetcode Word Search II
- 第四周项目3-单链表应用(2)
- HDU1576 A/B 求乘法逆元模版
- (九)ArcGIS API For Javascript调用结果地图服务
- ViewPager冲突之(ViewPager与ViewPager+Fragment滑动栏冲突)
- 开始写博客激励自己游戏引擎程序员之路
- leetcode 212. Word Search II
- 一个C程序是如何生成的
- es6的新特性(一)
- 关于Virtualbox下安装Linux系统
- python学习之 12306的一个小爬虫
- 深入理解javascript(4):__proto__
- STL容器之Vector
- java编程思想(七)总结
- 暴露年龄