Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must is constructed from letters of sequentially adjacent cell, where "adjacent" cells is those horizontally or Vertically neighboring. The same letter cell is used more than once in a word.
For example,
Given words = and ["oath","pea","eat","rain"]
board =
[ [' O ', ' a ', ' a ', ' n '], [' e ', ' t ', ' a ', ' e '], [' I ', ' h ', ' K ', ' R '], [' I ', ' f ', ' l ', ' V ']]
Return ["eat","oath"]
.
Note:
You may assume this all inputs is consist of lowercase letters a-z
.
similar:79. Word Search
1 Public classSolution {2 classTrie {3 trie[] Childs;4String Word;//can not be Boolean5 PublicTrie () {6Childs =NewTrie[26];7 }8 }9 Private voidBuildtrie (String Word, Trie node) {Ten for(CharC:word.tochararray ()) { One inti = C-' a '; A if(Node.childs[i] = =NULL) Node.childs[i] =NewTrie (); -node =Node.childs[i]; - } the -Node.word =Word; - } - + PublicList<string> Findwords (Char[] board, string[] words) { - if(Board.length = = 0 | | board[0].length = = 0 | | words.length = = 0) + return NewLinkedlist<string>(); A atlinkedlist<string> ret =NewLinkedlist<string>(); - -Trie root =NewTrie (); - for(String word:words) { - Buildtrie (Word, root); - } in - for(inti = 0; i < board.length; i++) { to for(intj = 0; J < Board[0].length; J + +) { + Dfs (board, Root, I, J, ret); - } the } * returnret; $ }Panax Notoginseng - Private voidDfsChar[] board, Trie Root,intRintC, linkedlist<string>ret) { the CharCH =Board[r][c]; + A if(ch = = ' # ' | | root.childs[ch-' a '] = =NULL)return; the +root = root.childs[ch-' a ']; - if(Root.word! =NULL) { $ Ret.add (Root.word); $Root.word =NULL;//de-duplicate - } - theBoard[r][c] = ' # '; - Wuyi if(r > 0) DFS (board, Root, r-1, C, ret); the - if(R < board.length-1) Dfs (board, Root, R + 1, C, ret); Wu - if(C > 0) DFS (board, Root, R, c-1, ret); About $ if(c < board[0].length-1) Dfs (board, Root, R, C + 1), ret); - -BOARD[R][C] =ch; - A } +}
212. Word Search II