leetcode 212. Word Search II
2016-09-26 21:06
288 查看
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; } };
相关文章推荐
- LeetCode 212. Word Search II
- Leetcode 79. Word Search & 212. Word Search II
- LeetCode 212. Word Search II(单词搜索)
- LeetCode 212. Word Search II
- Leetcode 212. Word Search II
- [LeetCode] 212. Word Search II 词语搜索 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 212 Word Search II 字典树 + 回溯
- 【leetcode】Word Search II(hard)★
- 212. Word Search II
- LeetCode() Word Search II
- 212. Word Search II
- 212. Word Search II
- Leetcode - Word Search II
- LeetCode解题笔记212 Word Search II