212. Word Search II
Hard
107368FavoriteShare
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"]思路就是将所有的word组成一棵trie树,然后对board中的每一个元素做dfs。
struct TrieNode { vector<TrieNode*> child = vector<TrieNode*>(26,NULL); bool isterm = false; }; class Solution { public: vector<string> findWords(vector<vector<char>>& board, vector<string>& words) { set<string> ans_set; TrieNode* root = new TrieNode(); for(int i = 0; i<words.size() ; ++i) { addtree(root,words[i]); } for(int i = 0; i < board.size(); ++i) { for(int j = 0; j < board[0].size(); ++j) { string s = ""; isword(i, j, root, board, s, ans_set); } } vector<string> ans(ans_set.begin(),ans_set.end()); return ans; } void addtree(TrieNode* r, const string& word) { for(int i = 0; i < word.size(); ++i) { if(r->child[word[i]-'a'] == NULL) r->child[word[i]-'a'] = new TrieNode(); r = r->child[word[i]-'a']; } r->isterm = true; } void isword(int i,int j, TrieNode* r, vector<vector<char>> board, string s,set<string>& se_word) { if(i < 0 || j < 0 || i >= board.size() || j >= board[0].size() || board[i][j] == ' ') return; if(r->child[board[i][j]-'a']) { s += board[i][j]; if(r->child[board[i][j]-'a']->isterm) { se_word.insert(s); } r = r->child[board[i][j]-'a']; char letter = board[i][j]; board[i][j] = ' '; isword(i-1, j, r, board, s, se_word); isword(i, j+1, r, board, s, se_word); isword(i+1, j, r, board, s, se_word); isword(i, j-1, r, board, s, se_word); board[i][j] = letter; } } };