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.
For example,
Givenwords=["oath","pea","eat","rain"]andboard=
Note:
You may assume that all inputs are consist of lowercase lettersa-z.
hint:
You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier?
If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem:Implement Trie (Prefix Tree)first.
2. Implementation
(1) Trie + Backtracking
classSolution {classTrieNode {char val;boolean isWord;TrieNode childNode[];publicTrieNode() { childNode =newTrieNode[26]; } }classTrie {TrieNode root;publicTrie() { root =newTrieNode(); }publicvoidadd(String word) {if (word ==null||word.length() ==0) {return; }TrieNode curNode = root;for (char c :word.toCharArray()) {int index = c -'a';if (curNode.childNode[index] ==null) {curNode.childNode[index] =newTrieNode();curNode.val= c; } curNode =curNode.childNode[index]; }curNode.isWord=true; } }publicList<String> findWords(char[][] board,String[] words) {List<String> res =newArrayList<>();if (board ==null||board.length==0|| words ==null||words.length==0) {return res; }Trie trie =newTrie();for (String word : words) {trie.add(word); }int m =board.length, n = board[0].length;int[][] directions = {{-1,0}, {1,0}, {0,-1}, {0,1}};StringBuilder word =newStringBuilder();for (int i =0; i < m; i++) {for (int j =0; j < n; j++) {searchWord(i, j,trie.root, word, words, directions, board, res); } }return res; }publicvoidsearchWord(int row,int col,TrieNode node,StringBuilder word,String[] words,int[][] directions,char[][] board,List<String> res) {if (row <0|| row >=board.length|| col <0|| col >= board[0].length|| board[row][col] =='#') {return; }char c = board[row][col];TrieNode curNode =node.childNode[c -'a'];if (curNode ==null) {return; }word.append(c);if (curNode.isWord) {curNode.isWord=false;res.add(word.toString()); } board[row][col] ='#';for (int[] direction : directions) {int nextRow = row + direction[0];int nextCol = col + direction[1];searchWord(nextRow, nextCol, curNode, word, words, directions, board, res); } board[row][col] = c;word.setLength(word.length() -1); }}