LeetCode-212. Word Search II
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.
Example:
Input:
board = [
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
words = ["oath","pea","eat","rain"]
Output: ["eat","oath"]
题解:
使用字典树存储所有单词,节省存储空间。
字典树的路径若为单词,则标记为单词,访问后置否去重。
class Solution {public: struct Trie { vector child; bool isWord; Trie(): child(vector(26, NULL)), isWord(false){} }; Trie* buildTree(vector &words) { Trie *root = new Trie(); for (int i = 0; i < words.size(); i++) { Trie *t = root; for (int j = 0; j < words[i].size(); j++) { if (t->child[words[i][j] - 'a'] == NULL) { t->child[words[i][j] - 'a'] = new Trie(); } t = t->child[words[i][j] - 'a']; } t->isWord = true; } return root; } void dfs(vector &res, vector>& board, int n, int m, int x, int y, Trie *t, string &s) { if (x < 0 || x >= n || y < 0 || y >= m || t == NULL || board[x][y] == 'O') { return; } if (t->child[board[x][y] - 'a'] == NULL) { return; } s += board[x][y]; t = t->child[board[x][y] - 'a']; if (t->isWord == true) { res.push_back(s); t->isWord = false; } char ch = board[x][y]; board[x][y] = 'O'; dfs(res, board, n, m, x + 1, y, t, s); dfs(res, board, n, m, x - 1, y, t, s); dfs(res, board, n, m, x, y + 1, t, s); dfs(res, board, n, m, x, y - 1, t, s); board[x][y] = ch; s.pop_back(); } vector findWords(vector>& board, vector& words) { Trie *t = buildTree(words); if (board.empty() == true || words.empty() == true) { return {}; } int n = board.size(), m = board[0].size(); vector res; string s; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { dfs(res, board, n, m, i, j, t, s); } } return res; }};
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
暂时没有评论,来抢沙发吧~