212. 单词搜索 II
Posted yuhong1103
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了212. 单词搜索 II相关的知识,希望对你有一定的参考价值。
1 class Trie 2 { 3 public: 4 bool is_end; //是否以该单词结尾 5 Trie* son[26]; //该节点儿子的个数 6 Trie() 7 { 8 is_end = false; 9 for(int i = 0;i < 26;i ++) son[i] = NULL; 10 } 11 12 /** Inserts a word into the trie. */ 13 void insert(string word) 14 { 15 auto p = this; 16 for(auto c : word) 17 { 18 int u = c - ‘a‘; 19 if(p->son[u] == NULL) p->son[u] = new Trie(); 20 p = p->son[u]; 21 } 22 p->is_end = true; 23 } 24 25 /** Returns if the word is in the trie. */ 26 bool search(string word) 27 { 28 auto p = this; 29 for(auto c : word) 30 { 31 int u = c - ‘a‘; 32 if(p->son[u] == NULL) return false; 33 p = p->son[u]; 34 } 35 return p->is_end; 36 } 37 38 /** Returns if there is any word in the trie that starts with the given prefix. */ 39 bool startsWith(string prefix) 40 { 41 auto p = this; 42 for(auto c : prefix) 43 { 44 int u = c - ‘a‘; 45 if(p->son[u] == NULL) return false; 46 p = p->son[u]; 47 } 48 return true; 49 } 50 }; 51 52 class Solution 53 { 54 public: 55 vector<string> res; 56 unordered_set<string> hash; 57 vector<string> findWords(vector<vector<char>>& board, vector<string>& words) 58 { 59 Trie trie; 60 for(auto a : words) trie.insert(a); 61 62 int m = board.size(); 63 int n = board[0].size(); 64 vector<vector<bool>> visited(m,vector<bool>(n,false)); 65 for(int i = 0;i < m;i ++) 66 { 67 for(int j = 0;j < n;j ++) 68 { 69 dfs(board,visited,"",i,j,trie); 70 } 71 } 72 return res; 73 } 74 void dfs(vector<vector<char>>& board,vector<vector<bool>>& visited,string str,int x,int y,Trie trie) 75 { 76 if(x < 0 || x >= board.size() || y < 0 || y >= board[0].size() || visited[x][y]) return; 77 str += board[x][y]; 78 if(!trie.startsWith(str)) return; 79 if(trie.search(str) && hash.find(str) == hash.end()) 80 { 81 res.push_back(str); 82 hash.insert(str); 83 } 84 85 visited[x][y] = true; 86 dfs(board,visited,str,x - 1,y,trie); 87 dfs(board,visited,str,x + 1,y,trie); 88 dfs(board,visited,str,x,y - 1,trie); 89 dfs(board,visited,str,x,y + 1,trie); 90 visited[x][y] = false; 91 } 92 93 };
以上是关于212. 单词搜索 II的主要内容,如果未能解决你的问题,请参考以下文章
[JavaScript 刷题] 树 - 单词搜索 II, leetcode 212